brandonscript brandonscript - 5 months ago 411
Swift Question

How do I write dispatch_after GCD in Swift 3?

In Swift 2, I was able to use

dispatch_after
to delay an action:

var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})


But this no longer seems to compile in Swift 3. What is the preferred way to write this in Swift 3 (using the new Dispatch API)?

Rob Rob
Answer

The syntax is now:

var dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.after(when: dispatchTime, execute: {
    // your function here
})

Or, more simply:

DispatchQueue.main.after(when: DispatchTime.now() + 0.1) {
    // your function here
}

If you enter your code and then choose "Edit" - "Convert" - "To Current Swift Syntax...", it will do this conversion for you.