Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Getting started with GCD in Swift 3

$
0
0

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.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
// Background thread
dispatch_async(dispatch_get_main_queue()) { () -> Void in
// UI Updates
}
}

Now, new syntax like below:

DispatchQueue.global().async {
// Background thread
DispatchQueue.main.async(execute: {
// UI Updates
})
}

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).

/*
- background : The background quality of service class.
- utility : The utility quality of service class.
- `default` : The default quality of service class.
- userInitiated : The user-initiated quality of service class.
- userInteractive : The user-interactive quality of service class.
- unspecified : The absence of a quality of service class.
*/
public enum QoSClass {
case background
case utility
case `default`
case userInitiated
case userInteractive
case unspecified
public init?(rawValue: qos_class_t)
public var rawValue: qos_class_t { get }
}

Work items

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

let workItem = DispatchWorkItem(qos: .userInitiated, flags: .assignCurrentContext) {
// Do stuff
}
DispatchQueue.main.async(execute: workItem)

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:

public static let barrier: DispatchWorkItemFlags

public static let detached: DispatchWorkItemFlags

public static let assignCurrentContext: DispatchWorkItemFlags

public static let noQoS: DispatchWorkItemFlags

public static let inheritQoS: DispatchWorkItemFlags

public static let enforceQoS: DispatchWorkItemFlags

dispatch_once

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

// Static
class Video {
static let sharedInstance = Video()
func doSomething(){
print("❤")
}
}

// Global constant.
let constant = Video()

// Global variable.
var variable: Video = {
let variable = Video()
variable.doSomething()
return variable
}()

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

let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC)))
     dispatch_after(delay, dispatch_get_main_queue()) { () -> Void in
// Do something
}

now, syntax is easy to use

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
// Do something
}

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

public enum DispatchTimeInterval {

         case seconds(Int)

         case milliseconds(Int)

         case microseconds(Int)

         case nanoseconds(Int)
     }

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.

let mainQueue = DispatchQueue.main
mainQueue.async {
dispatchPrecondition(condition: .notOnQueue(mainQueue))
// This code won't execute
}
let queue = DispatchQueue.global()
queue.async {
dispatchPrecondition(condition: .onQueue(queue))
// This code will execute
}

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.

Viewing all articles
Browse latest Browse all 595

Trending Articles