🎓 A1Learner
🔍
0 of 27 lessons completed

Swift Async Await in Depth

An async function can pause its work while it waits for a result. The await keyword marks each point where execution pauses and then continues with the returned value.

A first async function

The function is marked async and returns a number. The call waits with await and the print shows the returned value.

func loadNumber() async -> Int {
    return 42
}
let number = await loadNumber()
print(number)

Two calls in sequence

Each call waits for its own result before the next line runs. The prints therefore follow the order of the calls.

func loadWord(_ word: String) async -> String {
    return word
}
let first = await loadWord("first")
print(first)
let second = await loadWord("second")
print(second)

An async function calling another

The total function awaits the base function inside its body. The outer call then returns the combined value.

func loadBase() async -> Int {
    return 20
}
func loadTotal() async -> Int {
    let base = await loadBase()
    return base + 22
}
let total = await loadTotal()
print(total)

Example

func fetchScore(for name: String) async -> Int {
    if name == "Ana" {
        return 9
    }
    return 5
}
let anaScore = await fetchScore(for: "Ana")
let boScore = await fetchScore(for: "Bo")
print(anaScore)
print(boScore)
print(anaScore + boScore)

Key points

  • The async mark sits before the return arrow in a function declaration.
  • A call to an async function needs await before the call.
  • Execution pauses at an await call and resumes with the returned value.
  • A program can await several calls one after another and keep their order.
  • An async function can await another async function inside its own body.
  • A value returned after a pause works like any other returned value.

In this example, fetchScore returns 9 for Ana and 5 for every other name. The program awaits the two calls in turn and prints each score. The last print adds the scores and shows 14.

Note

the programs in this lesson await calls in sequence so the printed order never changes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does await do at a call to an async function?