The timer does not work on the Swift 3.0 playground

Work on the 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 prints on the console. I read How can I use NSTimer in Swift? , and most of the use of the timer that I saw in answers and tutorials online includes 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 is printed on the console. If I add timer.fire() , I get console fingerprints, but obviously this defeats the target. What do I need to change to start the timer?

EDIT:

So adding CFRunLoopRun() after I called the run method for my Test structure did the trick. Many thanks to those who answered, especially @AkshayYaduvanshi (who commented on me pointed to CFRunLoopRun() ) and @JoshCaswell (whose answer was triggered by the fact that I only work with the start cycle).

+5
source share
2 answers

You need to run a run loop.

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

The timer does nothing if there is no duty cycle input. The program just ends.

Timer link :

Timers work in conjunction with trigger cycles. [...] it only works when one of the modes of the start cycle to which the timer has been added is running, and it can check whether the timers for the timers have passed.

+5
source

Your first version works if you allow the playground to work unlimitedly through PlaygroundSupport :

 import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true let timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in print("Timer Fired at: \(timer.fireDate)") } 

Adding a manual loop cycle also works and may be required sometimes, but in your case this simple instruction is enough for the timer to work correctly.

+15
source

Source: https://habr.com/ru/post/1258227/


All Articles