Monthly

Categories

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.

dispatch_once

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

publicextensionDispatchQueue{

private staticvar_tokenTracker=[String]()

public classfunconce(executeToken:String,block:@noescape(Void)-&gt;Void){

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:

1

2

3

4

5

6

7

DispatchQueue.global(attributes:.qosDefault){

// Do background work

DispatchQueue.main.async{

// Do main UI work

}

}

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:

1

2

3

4

DISPATCH_QUEUE_PRIORITY_HIGH==.qosUserInitiated

DISPATCH_QUEUE_PRIORITY_DEFAULT==.qosDefault

DISPATCH_QUEUE_PRIORITY_LOW==.qosUtility

DISPATCH_QUEUE_PRIORITY_BACKGROUND==.qosBackground

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.