Updated for Xcode 14.2
Swift’s Task
struct has a static sleep()
method that will cause the current task to be suspended for at least some number of nanoseconds. Yes, nanoseconds: you need to write 1_000_000_000 to get 1 second. You need to call Task.sleep()
using await
as it will cause the task to be suspended, and you also need to use try
because sleep()
will throw an error if the task is cancelled.
For example, this will make the current task sleep for at least 3 seconds:
try await Task.sleep(nanoseconds: 3_000_000_000)
Important: Calling Task.sleep()
will make the current task sleep for at least the amount of time you ask, not exactly the time you ask. There is a little drift involved because the system might be busy doing other work when the sleep ends, but you are at least guaranteed it won’t end before your time has elapsed.
Using nanoseconds is a bit clumsy, but Swift doesn’t have an alternative at this time – the plan seems to be to wait for a more thorough review of managing time in the language before committing to specific API.
In the meantime, we can add small Task
extensions to make sleeping easier to accomplish. For example, this lets us sleep using seconds as a floating-point number:
extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
let duration = UInt64(seconds * 1_000_000_000)
try await Task.sleep(nanoseconds: duration)
}
}
With that in place, you can now write Task.sleep(seconds: 0.5)
or similar.
Calling Task.sleep()
automatically checks for cancellation, meaning that if you cancel a sleeping task it will be woken and throw a CancellationError
for you to catch.
Tip: Unlike making a thread sleep, Task.sleep()
does not block the underlying thread, allowing it pick up work from elsewhere if needed.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.