Topics

Topics

We've covered GCD a few times back in Bites #85 & #35. This year, GCD is getting a huge overhaul that brings it into the modern world of Swift. Today we'll take a look at what's changed, let's dive in.

Topics

Topics

Grand Central Dispatch is the name of Apple's collection of task concurrencyfunctions in libdispatch. GCD (as it's often called) is packed full of interesting features involving concurrency, queuing, timers, and more. Let's dive in and take a look at some simple and common use cases:

Common Usage

One of the most common ways to use GCD is to hop to a background queue to do some work, then hop back to the main queue to update the UI:

Dispatch After

We can also easily wait a specified amount of time, then run some code. Here we'll use this technique to pop back to the previous view controller a quick "beat" after the user selects an an option in a table view controller. (As seen in many apps, including Settings.app):

Topics

Topics

Grand Central Dispatch is a wonderful way to write asynchronous code in your app. It's actual API however, can sometimes be a bit, well, let's call it "dry". Async is a Swift library by Tobias Due Munk that adds some much-welcomed syntactic sugar to Grand Central Dispatch. Async's core API is simple enough to be understood in a single line of code, so let's look at some other fun things it can do:

Chain Blocks

Async.background{// Runs on the background queue}.main{// Runs on the main queue, but only after// the previous block returns}

Delayed Execution

Async.main(after:0.5){// executed on the main queue after 500 ms}.background(after:0.4){// executed on the background queue// 400 ms after the first block completes}

Cancel Blocks

letcomputeThings=Async.background{computeSomethingBig()}letcomputerOtherThings=computeThings.background{// this sucker is about to get cancelled}Async.main{computeThings.cancel()// this won't do anything// you can only cancel blocks that haven't yet started executing!computerOtherThings.cancel()// this second block *would* in fact get cancelled,// since it hasn't started executing yet}