Swift:使用scheduledTimerWithTimeInterval调用额外参数

Kev*_* Py 1 selector nstimer swift watchkit

我创建了一个简单的WatchApp节拍器.我使用NSTimer和.scheduledTimerWithTimeInterval,我在调用中有一个错误Extra Argument'selector'

谢谢你的回答

func playBeat() {

        if(self.State == true) {
            self.State == false
            [labelPlayPause.setTitle("Pause")]
        } else {
            self.State == true
            [labelPlayPause.setTitle("Play")]
        }

        BPMValue = 10
        var BPMInt:Int = Int(BPMValue)
        let value = "\(BPMInt) BPM"
        labelBPM.setText(value)
        let aSelector: Selector = "playBeat"

        dispatch_async(dispatch_get_main_queue(), {
            NSTimer.scheduledTimerWithTimeInterval(60/self.BPMValue, target:self, selector: aSelector, userInfo:nil, repeats:false)
        })

    }
Run Code Online (Sandbox Code Playgroud)

Ash*_*lls 6

这是来自Swift的错误消息!

这实际意味着您需要确保每个函数参数的类型与传递的值的类型相匹配.

在你的情况下,BPMValue是一个Float,并scheduledTimerWithTimeInterval期待和NSTimeInterval作为它的第一个参数.注意NSTimeInterval(Double)Float并不等同.在Objective-C中,您获得了隐式转换,这在Swift中不会发生.

尝试

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(60/self.BPMValue), target:self, selector: aSelector, userInfo:nil, repeats:false)
Run Code Online (Sandbox Code Playgroud)

作为旁注,您可以使用Swift中的代码更简洁一些:

func playBeat() {

    if State {          // If State is a Bool, you can lose the '== true'
        State = false   // Must use set not comparison operator. No need to refer to 'self'.
        labelPlayPause.setTitle("Pause")
    } else {
        State = true  // Must use set not comparison operator.
        labelPlayPause.setTitle("Play")
    }

    BPMValue = 10
    var BPMInt = Int(BPMValue)    // Int Type is inferred
    let value = "\(BPMInt) BPM"
    labelBPM.setText(value)
    let aSelector: Selector = "playBeat"

    dispatch_async(dispatch_get_main_queue(), {
        NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(60/self.BPMValue), target:self, selector: aSelector, userInfo:nil, repeats:false)
    })

}
Run Code Online (Sandbox Code Playgroud)