Swift: Using Grand Central Dispatch (GCD)

Grand Central Dispatch is a C API unlike other APIs that expose Objective-C classes. However, that doesn’t mean you can’t call GCD functions, or any other C API functions, directly from Swift. The C API functions are exposed to Swift just like they are in Objective-C. You can just call them like any other Swift function.

Here’s an example of a very common thing to do with GCD. Dispatch some code to the main thread asynchronously.

        dispatch_async(dispatch_get_main_queue(), {

            println(“I got dispatched!”)


The call looks very similar to what you do in Objective-C. The only different is that you don’t need the block (^) syntax required by Objective-C. You can even make it a little prettier in Swift by using the trailing closer syntax since the last argument is a closure.

        dispatch_async(dispatch_get_main_queue()) {

            println(“I got dispatched!”)