将 NSTimer 与 "let" 一起使用?
Use NSTimer with "let"?
您好,我正在尝试在 Swift 2.0 项目的 class 中使用 NSTimer。我想为时间间隔使用 let
常量,但它总是显示错误 "string is not convertible to stringLiteralConvertible"。当我使用一个简单的数字时它可以工作,但我需要一个常量
func setupLocationUpdateInterval(seconds: Int)
{
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "startUpdatingLocation", userInfo: nil, repeats: true)
}
错误看起来是错误的。 (你从 Swift 得到的错误消息通常与问题的真正原因完全无关,只是告诉你 "there's something wrong with this line. Figure out what it is an fix it." 这比这样的错误要好,因为至少那样你不会认为错误消息实际上提供了有用的信息。)
NSTimer.scheduledTimerWithTimeInterval
方法需要一个双精度的间隔值。
假设我对 真实 问题的看法是正确的,您可以更改您的函数以将秒作为双精度,或者在调用 [=10 时将其转换为双精度=].
替换行:
func setupLocationUpdateInterval(seconds: Int)
行:
func setupLocationUpdateInterval(seconds: NSTimeInterval)
或者如果你想在某处使用 let 常量,确保它的类型是 NSTimeInterval
。
您好,我正在尝试在 Swift 2.0 项目的 class 中使用 NSTimer。我想为时间间隔使用 let
常量,但它总是显示错误 "string is not convertible to stringLiteralConvertible"。当我使用一个简单的数字时它可以工作,但我需要一个常量
func setupLocationUpdateInterval(seconds: Int)
{
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "startUpdatingLocation", userInfo: nil, repeats: true)
}
错误看起来是错误的。 (你从 Swift 得到的错误消息通常与问题的真正原因完全无关,只是告诉你 "there's something wrong with this line. Figure out what it is an fix it." 这比这样的错误要好,因为至少那样你不会认为错误消息实际上提供了有用的信息。)
NSTimer.scheduledTimerWithTimeInterval
方法需要一个双精度的间隔值。
假设我对 真实 问题的看法是正确的,您可以更改您的函数以将秒作为双精度,或者在调用 [=10 时将其转换为双精度=].
替换行:
func setupLocationUpdateInterval(seconds: Int)
行:
func setupLocationUpdateInterval(seconds: NSTimeInterval)
或者如果你想在某处使用 let 常量,确保它的类型是 NSTimeInterval
。