🎓 A1Learner
🔍
0 of 27 lessons completed

Swift Async Let

An async let declaration starts work right away and binds a name to its future result. The program reads that result later with await at the point where the value is needed.

A single async let

The declaration starts the load and the program moves on at once. The read later waits with await and prints the returned number.

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

Two results in a fixed order

Both loads start before either result is read. The program collects the first result and then the second, so the prints keep that order.

func loadValue(_ n: Int) async -> Int {
    return n * 10
}
async let first = loadValue(1)
async let second = loadValue(2)
let firstResult = await first
let secondResult = await second
print(firstResult)
print(secondResult)

Work between the start and the read

The loop runs while the load is in flight. The count prints first, and the awaited word prints after it.

func loadWord() async -> String {
    return "ready"
}
async let word = loadWord()
var count = 0
for _ in 1...3 {
    count += 1
}
print(count)
let result = await word
print(result)

Collecting in a chosen order

Both loads start together at their declarations. The program reads the second result first, so the prints follow the read order.

func loadLabel(_ text: String) async -> String {
    return text
}
async let first = loadLabel("first")
async let second = loadLabel("second")
let secondResult = await second
let firstResult = await first
print(secondResult)
print(firstResult)

Example

func fetch(_ n: Int) async -> Int {
    return n
}
async let first = fetch(10)
async let second = fetch(20)
async let third = fetch(12)
let firstResult = await first
let secondResult = await second
let thirdResult = await third
print(firstResult + secondResult + thirdResult)

Key points

  • The async let keywords start a piece of work without pausing at that line.
  • Other work can run between the declaration and the read.
  • Reading an async let value uses await just like an async call.
  • Several async let declarations can be in flight at the same time.
  • Collecting the values in a chosen order prints them in that same order.

In this example, three loads start one after another with async let. The program then collects the results in the order first, second, and third. The print adds the three values and shows 42.

Note

the programs in this lesson collect every result in a fixed order so the printed order never changes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does an async let declaration do when it runs?