Swift Tutorial · Swift Concurrency · Lesson 22 of 30

Swift async and await

Write asynchronous code with async functions, await, async let and Task.

Create a free account to save this page, take notes and track your progress. Sign in

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.

async and await
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.

async let
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?

  1. Declares a constant that is computed lazily
  2. Starts a child task right away; you await its result later
  3. Blocks the thread
  4. Creates a global variable
Show answer

Answer: Starts a child task right away; you await its result later

Was this page helpful?