Swift : Extra Argument in call with scheduledTimerWithTimeInterval

走远了吗. 提交于 2019-12-11 08:02:46

问题


I create a simple WatchApp Metronome. I use NSTimer with .scheduledTimerWithTimeInterval, and I have an error Extra Argument 'selector' in call

Thanks for your answers

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:


This is a poor error message from Swift!

What this really means is that you need to ensure the types of each function parameter match the types of the values passed.

In your case, BPMValue is a Float, and scheduledTimerWithTimeInterval is expecting and NSTimeInterval as its first parameter. Note that NSTimeInterval (Double) and Float are not equivalent. In Objective-C you get an implicit conversion, this doesn't happen in Swift.

Try

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

As a side note, you can be a little more terse with your code in 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)
    })

}


来源:https://stackoverflow.com/questions/27875005/swift-extra-argument-in-call-with-scheduledtimerwithtimeinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!