#10: Executing closures with a delay in Swift 3

There are a few ways to execute a closure with a delay, you could use the old Timer class and its sheduledTimer method or even create a DispatchSource scheduling a one time event with scheduleOneshot, but you can have the same result simply using the Grand Central Dispatch and its queues:

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
    // Your code that will be executed with a 4 seconds delay

Note how after SE-0088 the GCD has now a more “object oriented” interface and how easily you can specify a dealine using DispatchTime and the DispatchTimeInterval enum.

This short post is one of the Swift Bites, click the link for more!

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.