Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer.scheduledTimerWithTimeInterval in Swift Playground

All the examples I've seen on using the "NSTimer.scheduledTimerWithTimeInterval" within Swift show using the "target: self" parameter, but unfortunately this doesn't work in Swift Playgrounds directly.

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

Here's an example referenced above that results in the 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()
like image 343
Chris Pietschmann Avatar asked Dec 03 '14 02:12

Chris Pietschmann


1 Answers

You really should not be using NSTimer these days. It's consumes a lot of resources, causes 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 playground does it's stuff you will need an equivalent of timer.fire() to force the code to execute immediately instead of after a 0 second delay. Here's how that works:

let printFrom1To1000 = { () -> Void in
  for counter in 0...1000 {
    var b = counter
  }
}

dispatch_after(0, dispatch_get_main_queue(), printFrom1To1000)

printFrom1To1000()
like image 200
Abhi Beckert Avatar answered Sep 21 '22 13:09

Abhi Beckert