async and await
suggest changeSwift 5.5 added async and await to the language. They let you write asynchronous code that reads top to bottom, like ordinary synchronous code, without completion handlers.
asyncmarks a function (or initializer, property getter, subscript, closure) that can suspend: pause while it waits for something, and resume later.awaitmarks the places where a call to anasyncfunction can suspend. These places are called suspension points.
Before Swift 5.5, asynchronous code used callbacks (see Completion Handler and Using closures for asynchronous coding) or work submitted to dispatch queues (see Running tasks in a Grand Central Dispatch GCD queue). These still work, but new APIs, including URLSession, file I/O in Foundation and most server-side frameworks, provide async versions.
The examples in this article were compiled with Swift 6.4 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 -parse-as-library main.swift
-parse-as-library is needed when a single file uses @main. In a Swift package (swift package init --type executable) you don't need any flags.
Declaring and calling an async function
Put async after the parameter list, before ->. Call the function with await:
func makeGreeting(for name: String) async -> String {
try? await Task.sleep(for: .milliseconds(500))
return "Hello, \(name)!"
}
@main
struct App {
static func main() async {
print("before")
let greeting = await makeGreeting(for: "Swift")
print(greeting)
print("after")
}
}
Output:
before
Hello, Swift!
after
The output appears in order. print("after") runs only after makeGreeting returns, even though the function waited half a second in the middle. There is no callback, and you don't need extra code to get the result back to the caller.
Task.sleep(for:) is an async function that suspends the current task for the given time without blocking a thread. It is the async version of sleep(). It is used throughout this article to stand in for real work, such as a network request.
An async main
A @main type can declare static func main() async (or async throws). The runtime starts the program inside an async context, so main can await directly.
In a main.swift file (top-level code, no @main) you can use await directly, at the top level:
func makeGreeting(for name: String) async -> String {
try? await Task.sleep(for: .milliseconds(500))
return "Hello, \(name)!"
}
print("before")
let greeting = await makeGreeting(for: "top-level code")
print(greeting)
Output:
before
Hello, top-level code!
The compiler checks await
You can only call an async function from an async context: another async function, an async main, top-level code, or a Task. Calling it from a regular function doesn't compile, even with await:
func makeGreeting(for name: String) async -> String {
return "Hello, \(name)!"
}
func greetEveryone() -> String {
return await makeGreeting(for: "everyone")
}
a4.swift:6:18: error: 'async' call in a function that does not support concurrency
5 | func greetEveryone() -> String {
| `- note: add 'async' to function 'greetEveryone()' to make it asynchronous
6 | return await makeGreeting(for: "everyone")
| `- error: 'async' call in a function that does not support concurrency
Inside an async function, forgetting await is also an error:
func greetEveryone() async -> String {
return makeGreeting(for: "everyone")
}
a5.swift:6:12: error: expression is 'async' but is not marked with 'await'
6 | return makeGreeting(for: "everyone")
| |- error: expression is 'async' but is not marked with 'await'
| `- note: call is 'async'
await is required so that anyone reading the code can see where a function might pause. It works like try, which shows where a function might throw.
One await covers the whole expression, so await a() + b() is fine when both calls are async.
async throws
A function can be both asynchronous and throwing. Write async throws in the declaration and try await at the call site, in that order:
import Foundation
struct User: Decodable {
let id: Int
let name: String
}
enum LoadError: Error {
case notFound(id: Int)
}
func loadUser(id: Int) async throws -> User {
try await Task.sleep(for: .milliseconds(200)) // pretend this is a network call
guard id > 0 else { throw LoadError.notFound(id: id) }
let json = #"{"id": \#(id), "name": "User \#(id)"}"#
return try JSONDecoder().decode(User.self, from: Data(json.utf8))
}
@main
struct App {
static func main() async {
do {
let user = try await loadUser(id: 42)
print("loaded:", user.name)
_ = try await loadUser(id: -1)
} catch LoadError.notFound(let id) {
print("no user with id \(id)")
} catch {
print("unexpected error:", error)
}
}
}
Output:
loaded: User 42
no user with id -1
Errors from async functions work like errors from synchronous ones: they propagate up through try, and you handle them with do / catch. With callbacks, every step has to check for an error and pass it on by hand.
Writing them in the wrong order produces a warning:
warning: 'try' must precede 'await'
Rewriting a completion-handler function as async
Here is a typical callback-based API and a function that calls it twice in a row:
import Foundation
enum FetchError: Error {
case badID(Int)
}
// Old style: the result is delivered later, to a callback.
func fetchScore(id: Int, completion: @escaping @Sendable (Result<Int, FetchError>) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 0.2) {
if id < 0 {
completion(.failure(.badID(id)))
} else {
completion(.success(id * 10))
}
}
}
// Two calls in a row: every step nests one level deeper
// and every error has to be forwarded by hand.
func totalScore(completion: @escaping @Sendable (Result<Int, FetchError>) -> Void) {
fetchScore(id: 1) { first in
switch first {
case .failure(let error):
completion(.failure(error))
case .success(let a):
fetchScore(id: 2) { second in
switch second {
case .failure(let error):
completion(.failure(error))
case .success(let b):
completion(.success(a + b))
}
}
}
}
}
let done = DispatchSemaphore(value: 0)
totalScore { result in
print("total:", result)
done.signal()
}
done.wait() // keep the program alive until the callback runs
Output:
total: success(30)
The same logic with async / await:
enum FetchError: Error {
case badID(Int)
}
func fetchScore(id: Int) async throws -> Int {
try await Task.sleep(for: .milliseconds(200))
if id < 0 { throw FetchError.badID(id) }
return id * 10
}
func totalScore() async throws -> Int {
let a = try await fetchScore(id: 1)
let b = try await fetchScore(id: 2)
return a + b
}
print("total:", try await totalScore())
do {
_ = try await fetchScore(id: -5)
} catch {
print("error:", error)
}
Output:
total: 30
error: badID(-5)
The async version is better in several ways:
- The code is flat. Each step is one line, with no nesting.
- The result is a return value and errors are thrown, so you don't need
Resultor acompletionparameter. - The compiler makes sure every path returns a value or throws. With callbacks, forgetting to call
completionon one path is a common bug: the caller waits forever and the compiler can't catch it. - The caller doesn't need a semaphore or another trick to wait for the result.
Wrapping a callback API you can't change
If the callback-based function comes from a library, wrap it with withCheckedThrowingContinuation (or withCheckedContinuation when it can't fail). The closure gets a continuation, and you resume it exactly once with the result:
import Foundation
enum FetchError: Error {
case badID(Int)
}
// A callback API we can't change (e.g. from a library).
func fetchScore(id: Int, completion: @escaping @Sendable (Result<Int, FetchError>) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 0.2) {
completion(id < 0 ? .failure(.badID(id)) : .success(id * 10))
}
}
// An async wrapper around it.
func fetchScore(id: Int) async throws -> Int {
try await withCheckedThrowingContinuation { continuation in
fetchScore(id: id) { result in
continuation.resume(with: result)
}
}
}
let score = try await fetchScore(id: 7)
print("score:", score)
Output:
score: 70
"Checked" means the runtime reports a bug if you resume the continuation twice, or never resume it. Continuations, AsyncStream and other ways to bridge callback and delegate APIs are covered in AsyncSequence, AsyncStream and continuations.
Suspension points are not threads
await doesn't create a thread and doesn't block one. When an async function reaches a suspension point that has to wait, such as a sleep, network I/O or a lock held by an actor, the function's state is saved and the thread is released to run other work. When the awaited result is ready, the function resumes, possibly on a different thread.
Async code runs on a small cooperative thread pool, with about one thread per CPU core. Because waiting tasks don't hold threads, a few threads can serve thousands of tasks.
This program measures three cases:
import Foundation
func work(_ i: Int) async -> Int {
try? await Task.sleep(for: .seconds(1))
return i
}
func slowSyncCall() {
Thread.sleep(forTimeInterval: 1) // blocks the current thread
}
func blockingWork(_ i: Int) async -> Int {
slowSyncCall() // don't do this in async code
return i
}
@main
struct App {
static func main() async {
let clock = ContinuousClock()
let cores = ProcessInfo.processInfo.activeProcessorCount
print("cores:", cores)
// 3 awaits in a row: one after another
var elapsed = await clock.measure {
_ = await work(1)
_ = await work(2)
_ = await work(3)
}
print("3 sequential awaits:", elapsed)
// 10_000 tasks, each sleeping 1 second
elapsed = await clock.measure {
var tasks: [Task<Int, Never>] = []
for i in 0..<10_000 {
tasks.append(Task { await work(i) })
}
var sum = 0
for t in tasks { sum += await t.value }
print("sum:", sum)
}
print("10000 sleeping tasks:", elapsed)
let n = cores * 2
elapsed = await clock.measure {
var tasks: [Task<Int, Never>] = []
for i in 0..<n {
tasks.append(Task { await blockingWork(i) })
}
for t in tasks { _ = await t.value }
}
print("\(n) blocking tasks:", elapsed)
}
}
Output on a machine with 24 logical CPUs:
cores: 24
3 sequential awaits: 3.0274721 seconds
sum: 49995000
10000 sleeping tasks: 1.0541312 seconds
48 blocking tasks: 2.025078 seconds
The output shows three things:
awaitdoesn't add parallelism. Threeawaits in a row run one after another, so they take 3 seconds.awaitmeans "wait here without blocking", not "run in the background". To run things at the same time you need more than one task, as described below.- Suspended tasks are cheap. 10,000 tasks that each sleep for a second finish in about 1 second. With one thread per task you would need 10,000 threads.
- Blocking a thread from async code is harmful.
Thread.sleepreally blocks the thread. The pool has only 24 threads, so 48 blocking tasks run in two batches and take 2 seconds. In real programs, a blocking call (synchronous file or network I/O, aDispatchSemaphore.wait(), a long CPU loop) slows down every other task in the program.
The compiler catches some of these mistakes. Calling Thread.sleep directly inside an async function doesn't compile:
error: class method 'sleep' is unavailable from asynchronous contexts
The example above gets around the check by calling it through the synchronous function slowSyncCall. That's exactly how it happens in real code, so the check isn't a guarantee.
Interleaving at suspension points
While one function is suspended, other code can run, even on a single thread. In the next example both tasks are created in main, so they inherit its isolation to the main actor and run one at a time. They still interleave, because each one gives up control at every await:
func step(_ name: String, _ n: Int, delay: Duration) async {
for i in 1...n {
print("\(name) step \(i)")
try? await Task.sleep(for: delay) // suspension point: other code can run here
}
}
@main
struct App {
static func main() async {
let a = Task { await step("A", 3, delay: .milliseconds(100)) }
let b = Task { await step("B", 3, delay: .milliseconds(150)) }
await a.value
await b.value
}
}
Output:
A step 1
B step 1
A step 2
B step 2
A step 3
B step 3
So shared state can change while a function is suspended. A value you read before an await may be different after it. Actors protect state from data races, but they don't protect you from this, which is called reentrancy. Actors covers it.
Running async work in parallel
To make independent calls run at the same time, start them as child tasks. For a fixed number of calls, the simplest way is async let:
func fetchScore(id: Int) async throws -> Int {
try await Task.sleep(for: .milliseconds(200))
return id * 10
}
let clock = ContinuousClock()
let elapsed = try await clock.measure {
async let a = fetchScore(id: 1) // starts running now
async let b = fetchScore(id: 2) // starts running now, in parallel
let total = try await a + b // wait for both
print("total:", total)
}
print("elapsed:", elapsed)
Output:
total: 30
elapsed: 0.2355047 seconds
The two calls overlap, so this takes 0.2 seconds instead of the 0.4 seconds of the sequential totalScore() above. async let, withTaskGroup for a dynamic number of jobs, and how errors and cancellation reach child tasks are covered in Structured concurrency with async let and TaskGroup.
Calling async code from synchronous code
A synchronous function can't await, but it can start a Task, which runs an async closure. The function returns right away, and the task runs on its own:
func fetchCount() async -> Int {
try? await Task.sleep(for: .milliseconds(100))
return 42
}
// A synchronous function, e.g. a callback from a UI framework.
func buttonTapped() -> Task<Void, Never> {
print("tapped")
return Task {
let count = await fetchCount()
print("count:", count)
}
}
@main
struct App {
static func main() async {
let task = buttonTapped()
print("buttonTapped returned")
await task.value // wait so the program doesn't exit early
}
}
Output:
tapped
buttonTapped returned
count: 42
This is how async code is usually started from a UI event handler or another synchronous callback. Task vs Task.detached, priorities and cancellation are covered in Tasks and cancellation.
async initializers, properties, subscripts and closures
async works in more places than functions:
protocol DataSource: Sendable {
func load(key: String) async throws -> String
}
struct SlowSource: DataSource {
func load(key: String) async throws -> String {
try await Task.sleep(for: .milliseconds(100))
return "value of \(key)"
}
}
struct Config: Sendable {
let source: any DataSource
// async initializer
init(source: any DataSource) async {
try? await Task.sleep(for: .milliseconds(100))
self.source = source
}
// read-only computed property with an async, throwing getter
var title: String {
get async throws {
try await source.load(key: "title")
}
}
// async subscript
subscript(key: String) -> String {
get async throws {
try await source.load(key: key)
}
}
}
// async function types and closures
func retry<T>(times: Int, _ operation: () async throws -> T) async throws -> T {
for attempt in 1..<times {
do {
return try await operation()
} catch {
print("attempt \(attempt) failed: \(error)")
}
}
return try await operation()
}
struct Flaky: Error {}
func loadFlaky() async throws -> String {
var calls = 0
return try await retry(times: 3) {
calls += 1
if calls < 3 { throw Flaky() }
return "ok after \(calls) calls"
}
}
@main
struct App {
static func main() async throws {
let config = await Config(source: SlowSource())
print(try await config.title)
print(try await config["color"])
print(try await loadFlaky())
let double: (Int) async -> Int = { n in
try? await Task.sleep(for: .milliseconds(10))
return n * 2
}
print(await double(21))
}
}
Output:
value of title
value of color
attempt 1 failed: Flaky()
attempt 2 failed: Flaky()
ok after 3 calls
42
Notes:
- Only read-only computed properties and subscripts can be
async, usingget asyncorget async throws. Stored properties and setters can't be async. - Protocol requirements can be
async. A synchronous method can satisfy anasyncrequirement, but not the other way around. - A closure becomes
asyncwhen its body containsawait. You can also give it an explicit type, such as(Int) async -> Int. - A synchronous function can be passed where an
asyncfunction type is expected.
Why Sendable shows up
In the Swift 6 language mode, main runs on the main actor, while plain async functions (load(key:), retry) run on the shared thread pool. Values passed between the two must be safe to share across threads. That's why DataSource and Config conform to Sendable, and why the closure that changes calls is created inside loadFlaky instead of inside main. Without Sendable the compiler reports errors such as:
error: non-Sendable type 'Config' cannot exit main actor-isolated context in call to nonisolated property 'title'
Sendable and Swift 6 data-race safety explains these rules and the Swift 6.2 settings that relax them.
Task.sleep in detail
Task.sleep has several forms:
@main
struct App {
static func main() async {
let clock = ContinuousClock()
let start = clock.now
try? await Task.sleep(for: .milliseconds(150))
try? await Task.sleep(for: .seconds(0.25))
try? await Task.sleep(nanoseconds: 100_000_000) // older API, Swift 5.5
try? await Task.sleep(until: start + .seconds(1), clock: clock)
try? await Task.sleep(for: .seconds(1), tolerance: .milliseconds(100))
print("elapsed:", clock.now - start)
// Task.sleep throws CancellationError when the task is cancelled
let task = Task {
do {
try await Task.sleep(for: .seconds(10))
print("woke up")
} catch {
print("sleep ended early:", error)
}
}
task.cancel()
await task.value
}
}
Output:
elapsed: 2.0160327 seconds
sleep ended early: CancellationError()
Task.sleep(for:)takes aDuration(.seconds,.milliseconds,.microseconds,.nanoseconds). It was added in Swift 5.7 and is the preferred form.Task.sleep(nanoseconds:)is the original Swift 5.5 API.Task.sleep(until:clock:)sleeps until a deadline. That is useful for running something at a fixed rate without drift.tolerance:lets the system delay the wakeup slightly so it can group timers together, which saves power.Task.sleepthrowsCancellationErrorwhen its task is cancelled, and returns early.try? await Task.sleep(...)ignores this. That's fine for demos, but in real code you usually wanttry await, so that cancellation stops the work.
Summary
- Mark a function
asyncwhen it can suspend. Call it withawait, or withtry awaitif it also throws. - You can only call async functions from an async context: an
asyncfunction, an async@main, top-level code, or aTask. awaitsuspends without blocking a thread. It doesn't run anything in parallel by itself. Useasync let, task groups or severalTasks for that.- Don't block threads in async code: no
Thread.sleep, semaphores or synchronous I/O. UseTask.sleep(for:)and async APIs. - Wrap callback APIs with
withCheckedThrowingContinuation, and rewrite your own completion handlers asasync throwsfunctions. - Shared state can change across an
await. Use actors to protect it, and in the Swift 6 language mode expect the compiler to requireSendablefor values that cross isolation boundaries.