Thursday, October 22, 2015 [Tweets] [Favorites]

GCD Sugar for Swift

Tobias Due Munk’s Async (via Swift Sandbox):

Async sugar looks like this:

Async.background {
    println("This is run on the background queue")
}.main {
    println("This is run on the main queue, after the previous block")
}

Instead of the familiar syntax for GCD:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
    println("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), {
        println("This is run on the main queue, after the previous block")
    })
})

The way it work is by using the new notification API for GCD introduced in OS X 10.10 and iOS 8. Each chaining block is called when the previous queue has finished.

Update (2015-10-23): See also Run.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment