iGetIt iGetIt - 26 days ago 10
Swift Question

How can I make a Swift 3.0 timer that calculates in hh:mm:ss:ms

I followed DuncanC's solution in Swift timer in milliseconds. Code below:

startTime = NSDate.timeIntervalSinceReferenceDate
Timer.scheduledTimer(timeInterval: 0.02,
target: self,
selector: Selector(("advanceTimer:")),
userInfo: nil,
repeats: true)


func advanceTimer(timer: Timer)
{
//Total time since timer started, in seconds
self.time = NSDate.timeIntervalSinceReferenceDate - startTime
//The rest of your code goes here
}


Xcode recommended I change
NSDate.timeIntervalSinceReferenceDate()
to
NSDate.timeIntervalSinceReferenceDate
and
startTime: NSTimeInterval
to
startTime: TimeInterval
for Swift 3.0.
My code produces the error:


Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyGame.GameScene advanceTimer:]: unrecognized selector sent to instance

Answer

In Swift 3 Selector syntax is changed, now you need to pass first parameter label with your action, your selector should be like #selector(self.advanceTimer(timer:)).

Timer.scheduledTimer(timeInterval: 0.02,
                     target: self,
                     selector: #selector(self.advanceTimer(timer:)),
                     userInfo: nil,
                     repeats: true)