Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 146 ยท Concurrency

async and await

Learn how to write and call async functions in Swift, use try await, run work together with async let, add async properties and initializers, and avoid slow sequential awaits.

In the previous lesson you saw why Swift replaced callbacks with async and await. This lesson goes through the rules and patterns in detail. By the end you will know how to declare asynchronous functions, how to call them in sequence or side by side, how errors travel through them, and which mistakes the compiler catches for you.

The idea is simple: async goes on the declaration of a function that might need to wait, and await goes on every call to such a function. Together they make waiting visible in the code, so you always know where your function may pause.

Declaring and calling an async function

Add the keyword async after the parameter list, before the return arrow. Call it with await.

Swift A first async function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inside greeting, the call to Task.sleep is itself async (and throws, so we use try? to ignore cancellation here). A function that calls await must be async itself, so the keyword spreads upward through the callers until it reaches an entry point that can start asynchronous work: top-level code in main.swift, a Task { }, or an @main type with an async main function.

An async function can also throw. The order of keywords is always async throws in the declaration, and try await at the call:

Swift async throws and try await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call succeeds. The second throws, control jumps to catch, and the print("reserved \(b)") line never runs. Everything you know about throws, do/catch, try? and try! works the same way (Error Handling).

What "sequential" means

Statements in an async function run in order. Each await waits for its call to finish before the next line starts. This is the biggest difference from callback code: the order you read is the order of execution.

Swift await runs in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Even though B is quicker than A, it does not start until A is done. The output is A, B, C, in the order written. That is exactly right when the steps depend on each other (the second needs the first's result). It is wasteful when they are independent, because the total time is the sum of the delays.

Running independent work together: async let

When two or more operations do not depend on each other, start them all and then wait for the results. async let creates a child task for the right-hand side and continues immediately; you await the variable when you need the value.

Swift async let starts work right away

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The three child tasks run together, so they finish in order of their delays: B, C, A. The results come back in the order you named them, [A, B, C], because you wrote the array that way. Total time is about the longest delay (150 ms), not the sum (250 ms). "all three started" prints first because async let does not wait.

You can mix async let with try. If the child throws, the error is raised at the await, not at the line that started it:

Swift Errors from async let surface at the await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

When b fails, the whole expression throws. Any async let that you have not yet awaited when the scope exits is cancelled and awaited automatically, so tasks never outlive the scope that created them. This property, called structured concurrency, is why child tasks are safe by default. See Tasks and Cancellation.

async let is for a fixed number of values that you write by name. For a loop or a number you only know at run time, use a task group.

Async properties, subscripts and initializers

Functions are not the only things that can wait. A read-only computed property can be async, and so can an initializer. The getter is marked get async (and get async throws), and reading the property requires await.

Swift Async properties and initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice where await appears: in front of the call to the initializer, and in front of the read of summary. There are no async setters: a property that waits can only be read. If you need to change something asynchronously, write a method.

Protocols can require async members too: func load() async throws -> Data in a protocol is satisfied by an async implementation, and a non-async function may also satisfy it. That makes it easy to write code that works with real network loaders and with simple test doubles. See Protocols.

Async closures and higher-order functions

A closure can be async too. Its type is written () async -> Int. Standard library methods like map accept closures that do not wait, so calling an async function inside map does not compile; use a for loop, a task group, or an async helper instead.

Swift Async closures as parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

retry takes an async throws closure and runs it up to three times. This kind of higher-order helper is common: retries, timeouts, logging wrappers. Because the closure is not @escaping, it can freely read and change the local calls variable.

Mistakes the compiler catches

Forgetting await is an error, not a silent bug. The compiler tells you where the code may suspend:

Swift Calling an async function without await (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real message is main.swift:6:17: error: expression is 'async' but is not marked with 'await', with a note that the call is async; the fix is to write await answer(). Calling an async function from a function that is not async fails the other way, as shown in the introduction.

Here is a mistake the compiler does not catch, because it is legal code that is merely slow: awaiting independent operations one after another in a loop.

Swift Sequential awaits add up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both give 60, but the loop takes roughly three times as long. We print booleans rather than exact times because timings change from run to run. When you see await inside a for loop over independent items, ask whether a task group would be better.

await and the rest of your program

Between the two ends of an await, other code can run. For your own local variables this is harmless: they belong to your task. For shared state it can surprise you, because the value you read before the await might be different afterward. In Swift 6, the compiler helps by refusing to let you share mutable state freely, and actors give you a safe way to share it.

A few more practical points:

  • await marks a possible suspension. A call to an async function that returns immediately will not actually pause, but you must still write await.
  • Awaiting is not blocking. The thread goes off to do other work. Do not confuse it with Thread.sleep or semaphores, which really do block.
  • Do not call blocking, slow synchronous functions inside async code and expect others to progress on a one-core machine. Long CPU work still occupies the thread.
  • Prefer Task.sleep(for:) over older sleep calls: it suspends instead of blocking and it respects cancellation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the async keyword go in a function declaration?

    You write func name(params) async -> Type, and with errors async throws.
  2. 2. How are a and b run in async let a = f(); async let b = g()?

    async let starts a child task immediately and continues; you await the value later.
  3. 3. When an async let child throws, where does the error appear?

    The error is stored and raised when you await the variable, using try await.
  4. 4. Which of these is NOT allowed for an async computed property?

    Computed properties can have async getters, but not async setters. Use a method for asynchronous updates.
  5. 5. A for loop awaits three independent 100 ms operations one after another. About how long does it take?

    Sequential awaits add up. Starting them with async let or a task group lets the waits overlap.

Summary

  • Declare waiting functions with async (async throws if they can fail); call them with await (try await).
  • Statements run in order; each await finishes before the next line starts.
  • Use async let to start independent work together and await the results later; errors appear at the await.
  • Unawaited async let children are cancelled and awaited at scope exit (structured concurrency).
  • Initializers and read-only properties (get async) can be async; there are no async setters.
  • Async closures have types like () async throws -> T; standard map does not accept them.
  • Forgetting await is a compile error; awaiting independent work in a loop is legal but slow.

Next: Tasks