Christopher Harris Christopher Harris - 5 months ago 20
Swift Question

Scheduling a Closure Expression in Swift

I'd like to be able to schedule a closure to be run at either an absolute or relative time in the future. I see that I can use

NSTimer
to schedule a selector to be called later, but this is not what I want. I would prefer to see something like this:

let timer = NSTimer.scheduleWithTimeInterval(
ti: NSTimerInterval(1.0),
action: {
// do something
}
)


Is there a built-in way to do something like this in Swift?

edit



I've now come across
dispatch_after
which seems to be more in line with what I want, but I'm open to other ideas.

Answer

dispatch_after should be a fine solution since there are no block based NSTimer methods.

Alternatively you could use (or create) a simple block based NSTimer category (or an extension in Swift): https://github.com/jivadevoe/NSTimer-Blocks

Comments