Search code examples
iosswiftconstantsnstimerswift2

Use NSTimer with "let"?


Hello I'm trying to use NSTimer in a class in Swift 2.0 project. I want to use a let constant for time interval, but it always shows the error "string is not convertible to stringLiteralConvertible". When I use a simple number it works, but I need a constant

func setupLocationUpdateInterval(seconds: Int)
{
    timer?.invalidate()
    timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "startUpdatingLocation", userInfo: nil, repeats: true)
}

Solution

  • The error looks like it's wrong. (The error messages you get from Swift are often totally unrelated to the real cause of the problem, and simply tell you "there's something wrong with this line. Figure out what it is an fix it." That would be better than errors like this, since at least then you wouldn't think the error message was actually providing useful information.)

    The NSTimer.scheduledTimerWithTimeInterval method wants an interval value that's a double.

    Assuming I am right about the real problem, You can either change your function to take seconds as a double, or cast it to a double in your call to NSTimer.scheduledTimerWithTimeInterval.