How to use background thread in swift?

Swift 3.0+

A lot has been modernized in Swift 3.0. Running something on a background queue looks like this:

DispatchQueue.global(qos: .userInitiated).async {
    print("This is run on a background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}

Swift 1.2 through 2.3

let qualityOfServiceClass = QOS_CLASS_USER_INITIATED
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on a background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})

Pre Swift 1.2 – Known issue

As of Swift 1.1 Apple didn’t support the above syntax without some modifications. Passing QOS_CLASS_USER_INITIATED didn’t actually work, instead use Int(QOS_CLASS_USER_INITIATED.value).

For more information see Apples documentation

Leave a Comment