Swift:使用 scheduleTimerWithTimeInterval 调用的额外参数 [英] Swift : Extra Argument in call with scheduledTimerWithTimeInterval
问题描述
我创建了一个简单的 WatchApp 节拍器.我将 NSTimer 与 .scheduledTimerWithTimeInterval 一起使用,但出现错误 Extra Argument 'selector' in call
I create a simple WatchApp Metronome. I use NSTimer with .scheduledTimerWithTimeInterval, and I have an error 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 的糟糕错误消息!
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.
在你的情况下,BPMValue
是一个 Float
,并且 scheduledTimerWithTimeInterval
是期望的,NSTimeInterval
作为它的第一个参数.请注意,NSTimeInterval
(Double
) 和 Float
不是等价的.在 Objective-C 中你会得到一个隐式转换,这在 Swift 中不会发生.
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.
试试
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(60/self.BPMValue), target:self, selector: aSelector, userInfo:nil, repeats:false)
<小时>
附带说明,您可以在 Swift 中使用更简洁的代码:
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)
})
}
这篇关于Swift:使用 scheduleTimerWithTimeInterval 调用的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!