One question I had today while listening to the latest episode of the Debug podcast was, “How will Grand Central Dispatch (GCD) work in Swift? Will GCD work in Swift?” With that question in mind I settled in, opened Xcode, and chose File > New > Project…
I chose a Single View Application since I wouldn’t need much of app to answer my question. I named it SwiftlyGCD and chose Swift as the language. I opened
ViewController.swift and started typing out
dispatch to see what would code-complete. Happily all of the wonderful GCD methods that we know and love appeared in the code-completion list in their Swift-equivalent notation.
dispatch_async() in Objective-C looks like so:
Whereas in Swift it appears like this:
As you can see we get a one for one translation from C to Swift thanks to Xcode 6. Additionally we get some extra niceties like named parameters. What does the code look like in usage?
1 2 3
The call to
dispatch_get_main_queue() is exactly the same as we’re used to, while the block syntax is simplified to just a pair of
Bottom line: GCD is fully available in Swift and works exactly as we’d expect. Way to go Apple!
He’s right! You can write the above dispatch like so:
1 2 3