#27: Dispatch After in Swift 5

To run something later, use asyncAfter on a dispatch queue:

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    self.statusLabel.text = "Done"
}

That schedules the block without blocking the current thread. It is the right choice for UI delays, retries, debouncing and lightweight timers.

If you might need cancellation, wrap the work in a DispatchWorkItem:

let work = DispatchWorkItem {
    refreshCache()
}

DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 5, execute: work)
work.cancel()

For repeating work, prefer Timer or a dedicated scheduling abstraction instead of recursively calling asyncAfter.


I'm also on Twitter and GitHub.

Subscribe via RSS.