James Lingo James Lingo - 1 month ago 33
Swift Question

Timer does not run in Swift 3.0 playground

Working in playground with Swift 3.0 I have this code:

struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}

let test = Test()
test.run()


But nothing is printing to console. I've read How can I use NSTimer in Swift? and most of the usage of timer that I've seen in answers and tutorials online involves a selector so I tried this:

class Test {
func run() {
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.peep), userInfo: nil, repeats: false)
}

@objc func peep() {
print("peep")
}
}

let test = Test()
test.run()


Still nothing seems to print to console. If I add
timer.fire()
, then I get the console prints, but obviously that defeats the purpose. What do I need to change to get the timer to run?

EDIT:

So adding
CFRunLoopRun()
after I called the
run
method for my
Test
struct did the trick. Much Thanks to those who answered, especially @AkshayYaduvanshi (who's comment pointed me to
CFRunLoopRun()
) and @JoshCaswell (whose answer brought up the fact that I timer only works with a run loop).

Answer

You need to start a run loop.

RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))

The timer doesn't do anything unless there is a working run loop accepting input. The program simply ends.

Timer reference:

Timers work in conjunction with run loops. [...] it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed.

Comments