【问题标题】:Swift : Extra Argument in call with scheduledTimerWithTimeIntervalSwift:使用 scheduleTimerWithTimeInterval 调用的额外参数
【发布时间】:2015-03-08 15:02:13
【问题描述】:

我创建了一个简单的 WatchApp 节拍器。我将 NSTimer 与 .scheduledTimerWithTimeInterval 一起使用,并且出现错误Extra Argument 'selector' in call

感谢您的回答

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

    }

【问题讨论】:

    标签: swift selector nstimer watchkit


    【解决方案1】:

    这是来自 Swift 的糟糕错误消息!

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

    在您的情况下,BPMValueFloatscheduledTimerWithTimeInterval 是预期的,NSTimeInterval 作为其第一个参数。请注意,NSTimeInterval (Double) 和 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)
        })
    
    }
    

    【讨论】:

    • 我不明白。 BPMValue 不是 Int,而是浮点数。我将 BPMValue 转换为 Int 以在 Label (BPMInt) 中显示。我在 NSTimer 中使用 BPMValue 作为浮点数,不是吗?
    • 不,NSTimeInterval 是 Double 的 typeAlias,不等同于 Float,所以不能给它传递浮点数。
    • 所以你必须添加 Double 或 NSTimeInterval,但不能添加 Float。
    • 添加了编辑,指出原始代码在两种情况下使用了比较运算符,而这两种情况应该使用集合运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2015-09-13
    • 2018-08-26
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多