NSTimer.scheduledTimerWithTimeInterval in Swift Playground

All the examples that I saw when using "NSTimer.scheduledTimerWithTimeInterval" in a Swift show using the "target: self" parameter, but unfortunately this does not work directly in Swift Playgrounds.

Playground execution failed: <EXPR>:42:13: error: use of unresolved identifier 'self' target: self, 

Here is an example that results in an error:

 func printFrom1To1000() { for counter in 0...1000 { var a = counter } } var timer = NSTimer.scheduledTimerWithTimeInterval(0, target: self, selector: Selector("printFrom1To1000"), userInfo: nil, repeats: false ) timer.fire() 
+6
source share
3 answers

You should not use NSTimer at this time. It consumes a lot of resources, leads to unnecessary battery drain, and the API lends itself to ugly code.

Use dispatch_after() instead:

 dispatch_after(0, dispatch_get_main_queue()) { () -> Void in for counter in 0...1000 { var b = counter } } 

Of course, since the timer will fire after the playground has loaded, you will need the equivalent of timer.fire() to force the code to execute immediately, and not after a 0-second delay. Here's how it works:

 let printFrom1To1000 = { () -> Void in for counter in 0...1000 { var b = counter } } dispatch_after(0, dispatch_get_main_queue(), printFrom1To1000) printFrom1To1000() 
+8
source

To run this directly on the Swift Playground, you need to embed the printFrom1To1000 function in the class, and then set an instance of this class in the "target:" parameter instead of using "self".

Here is a complete working example:

 class myClass: NSTimer{ func printFrom1To1000() { for counter in 0...1000 { var b = counter } } } let myClassInstance = myClass() var timer = NSTimer.scheduledTimerWithTimeInterval(0, target: myClassInstance, selector: Selector("printFrom1To1000"), userInfo: nil, repeats: false ) timer.fire() 
+3
source

If you already have an object that you are referencing (for example, updating a label), you can extend this type and use this function as a Selector. I find this easier than creating an entire new class and instantiating a new object from it.

 extension SKLabelNode { func updateMe() { count++ label.text = "\(count)" } } var timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: label, selector: Selector("updateMe"), userInfo: nil, repeats: true) timer.fire() 
0
source

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


All Articles