July 21, 2016 - No Comments!

Grand Central Dispatch in Swift 3

For years Grand Central Dispatch (or GCD for short) was one of the most unintuitive APIs throughout iOS SDK and yet it was the most essential set of APIs for a modern iOS application, that's about to change with the release of Swift 3.

Swift 3 brings the most fundamental changes to the core APIs and frameworks throughout macOS, iOS, watchOS and tvOS in general, with it most of the changes are being very appreciated throughout the community, with GCD being one of them.


One of the most notable changes in Swift 3 is the deprecation of dispatch_once, of course it was quite useful for code that were to be executed only once, but with most of Swift's constructs it can be easily replaced with either lazily initialized globals or static properties. We can write elegant extensions to DispatchQueue like the one below:

Its usage is quite simple:


How we were used to work with dispatch in the past was to first choose the dispatch method and then select which queue we wanted to dispatch to, with Swift 3 this order has been reversed.

How we used to dispatch a global queue asynchronously and get back to update UI in the main thread in Swift 2.2 was the following:

In Swift 3 we have to write the following code in order to execute a task in background and update UI in the main thread:

Queue attributes

As you have probably noticed that the quality of service is replacing the old priority attributes and it is a Swift option set and can include several options such as concurrent vs serial, memory management and quality of service (such as .qosDefault, .qosUserInteractive, .qosUserInitiated, .qosUtility and .qosBackground).

How it maps to the old priority attributes is the following:

Memory and activity management options are new for this year's OS release for which I will go in depth in a later post.

Dispatch preconditions

As with most Swift's APIs we have new additions and dispatch preconditions are one of them which are pretty useful to write safe code. Dispatch preconditions are a way to check the expected thread before executing code, in the past we have used dispatch_assert_queue(dispatch_queue_t queue); to verify that the current block is executing on our expected dispatch queue.

In Swift 3 we can proof-check the above-written code as follows:

To learn more about Swift 3 and Grand Central Dispatch, head out to Apple's WWDC 2016 talk on the matter: https://developer.apple.com/videos/play/wwdc2016/720/

Published by: Rolling Rabbits in Tech Talks, iOS, Swift

Comments are closed.