Swift:使用scheduledTimerWithTimeInterval调用额外参数

时间:2015-01-10 10:09:36

标签: swift selector nstimer watchkit

我创建了一个简单的WatchApp节拍器。我使用NSTimer和.scheduledTimerWithTimeInterval,我在调用额外参数'选择器'时出现错误

感谢您的回答

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)
        })

    }

1 个答案:

答案 0 :(得分:6)

这是来自Swift的错误消息!

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

在您的情况下,BPMValueFloatscheduledTimerWithTimeInterval期待并且NSTimeInterval是其第一个参数。请注意,NSTimeIntervalDouble)和Float不相同。在Objective-C中,你得到一个隐式转换,这在Swift中不会发生。

尝试

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

作为旁注,你可以在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)
    })

}