NSTimer
is a great example of an over-verbose, outdated Objective-C API. To run a simple line of code after a delay, you need to write a lot of boilerplate crap.
How about this:
NSTimer.schedule(5.seconds) {
println("Hello world!")
}
So much better. How about a timer that repeats every second? Swift supports optional parameters, so we could do repeat: true
, but how about:
NSTimer.schedule(every: 1.second) {
println("Hello world!")
}
Sweet. But what if you want to schedule the timer yourself? (e.g. for event tracking run loop mode)? Just cut the .schedule
part out:
let timer = NSTimer(every: 1.second) { println("Hello world!") }
Want to use a separate method after all? No problem:
func printFoo() {
println("Hello world!")
}
NSTimer.schedule(1.second, block: printFoo)
(after all, functions and methods are just named closures)
PS. I wrote something very similar in Objective-C before.
Previously in Swift Extensions:
Great job!