Getting started with GCD in Swift 3

Swift 3 brings with it many improvements to GCD (Grand Central Dispatch) syntax and usage.Let’s see what’s new things.


dispatch_async

GCD patterns is to perform work on a global background queue and update the UI on the main queue as soon as the work is done.

Previously, we have to choose dispatch method (sync vs async) and then the queue we wanted to dispatch our task to. Now GCD reverses this order – select the queue and then apply a dispatch method.

Now, new syntax like below:

Queue attributes

Queues now take attributes on init. This is a Swift OptionSet and can include queue options such as serial vs concurrent, memory and activity management options and the quality of service (QoSClass.default, QoSClass.userInteractive, QoSClass.userInitiated, QoSClass.utility and QoSClass.background).

Work items

Queues are not the only part of GCD to get a Swift OptionSet. There’s an updated Swift syntax like below:

A work item can now declare a quality or service and/or flags on init. Both of these are optional and affect the execution of the work item. The flags are an option set that includes the following options:

dispatch_once

In Swift 3, dispatch_once is deprecated and should be replaced with either global or static variables and constants.

dispatch_time_t

dispatch_time_t was a function that translated a specified time to a UInt64 that could be provided to a queue.

Previously, we are using NSEC_PER_SEC

now, syntax is easy to use

The .seconds is part of a new enum called DispatchTimeInterval. The cases have an associated value representing the count. It currently supports:

dispatchPrecondition

Also we have new dispatch preconditions. Allow you to check whether or not you are on the expected thread before executing code. This is particularly useful for functions that update the UI and must be executed on the main queue.

There are many more GCD improvements included in Swift 3 . To learn more about GCD go deeper:

  1. apple/swift-evolution
  2. Dispatch
  3. Concurrent Programming With GCD in Swift 3 – WWDC – 2016 – Video
Sandeep Joshi

Sandeep Joshi | iOS Developer

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.
mm

Sandeep Joshi iOS Developer

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.

Comments are closed.

Top