#47: Wait or Delay in Swift

There are two very different meanings of “wait” in Swift.

If you want to schedule work later, use DispatchQueue.asyncAfter:

DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
    print("Later")
}

If you call Thread.sleep, you block the current thread:

Thread.sleep(forTimeInterval: 1.5)

That is occasionally fine in scripts or background worker code, but it is almost always the wrong thing to do on the main thread because it freezes the UI.

So for app code, “delay” usually means asyncAfter, not sleep. If you are specifically scheduling a closure to run later, see also #27: Dispatch After in Swift 5.


I'm also on Twitter and GitHub.

Subscribe via RSS.