Swift Tutorial · Swift Concurrency · Lesson 22 of 30
Swift async and await
Write asynchronous code with async functions, await, async let and Task.
async functions
An async function can suspend while it waits (for the network, a file or a timer) without blocking a thread.
Calls to it are marked await. Task.sleep simulates slow work here.
func fetchUser(id: Int) async -> String {
try? await Task.sleep(for: .milliseconds(100)) // pretend network call
return "user-\(id)"
}
print("start")
let user = await fetchUser(id: 7)
print("got \(user)")
Output
start got user-7
Run this on your computer — see “Get Started” for setup.
Running work concurrently
async let starts child tasks that run at the same time; you await their results later. The two 300 ms calls
below finish in about 300 ms, not 600.
func fetchProfile() async -> String {
try? await Task.sleep(for: .milliseconds(300))
return "Ana"
}
func fetchOrderCount() async -> Int {
try? await Task.sleep(for: .milliseconds(300))
return 3
}
let clock = ContinuousClock()
let elapsed = await clock.measure {
async let name = fetchProfile() // both start now
async let orders = fetchOrderCount()
print("\(await name) has \(await orders) orders")
}
print(elapsed < .milliseconds(550) ? "ran concurrently" : "ran sequentially")
Output
Ana has 3 orders ran concurrently
Run this on your computer — see “Get Started” for setup.
Test yourself
What does async let do?
Declares a constant that is computed lazilyStarts a child task right away; you await its result laterBlocks the threadCreates a global variable
Show answer
Answer: Starts a child task right away; you await its result later