On a Swift forecast screen that needs a forecast and an air-quality reading, how do two sequential awaits differ from two `async let` bindings?
answer
- when does the second request start
- one child task per binding
- await where the value is used
- let only, local only
- dependent calls stay sequential
basics
~20 sSequential awaits run the requests in turn, so the wait is their sum. Each async let starts its call at once as a child task, awaited where the value is used, so the wait is roughly the slower request.
solid answer
~50 sWith `let forecast = try await fetchForecast()` followed by `let air = try await fetchAirQuality()`, the second request starts only after the first returns: two one-second calls take about two seconds. Writing `async let forecast = fetchForecast()` and `async let air = fetchAirQuality()` starts each call as a **child task** right on its own line, without suspending; the function suspends only where it reads them, as in `try await (forecast, air)`, so the pair takes about one second. The rules: `async let` works only in an async context, only with `let`, and only on local declarations; reading it needs `await` (and `try` if its initializer throws). Keep sequential awaits when the second call needs the first call's result. For a number of calls known only at run time, a task group is the tool (covered in the lesson on tasks).
code
swift · 25 linesstruct Forecast: Sendable { let summary: String }
struct AirQuality: Sendable { let index: Int }
func fetchForecast() async throws -> Forecast {
try await Task.sleep(for: .seconds(1))
return Forecast(summary: "Sunny")
}
func fetchAirQuality() async throws -> AirQuality {
try await Task.sleep(for: .seconds(1))
return AirQuality(index: 42)
}
// About 2 s: the second request starts only after the first one returns.
func loadSequentially() async throws -> (Forecast, AirQuality) {
let forecast = try await fetchForecast()
let air = try await fetchAirQuality()
return (forecast, air)
}
// About 1 s: each async let starts a child task on its own line.
func loadInParallel() async throws -> (Forecast, AirQuality) {
async let forecast = fetchForecast()
async let air = fetchAirQuality()
return try await (forecast, air)
}go deeper
Recall that sequential awaits run one after another, that async let starts work at once, and that each async let value is read with await.
Explain that each async let is a child task started on its own line, why the pair takes the slower call's time, and the let-only, local-only rules.
Choose between sequential awaits, async let and task groups by dependency and count, and order the awaits so errors surface sensibly.
Judge where a screen's latency budget comes from and when parallel requests are worth the extra load they put on the backend.
## Sequential awaits An `await` suspends the function until the awaited call returns. Two awaits in a row are therefore **sequential**: in ```swift let forecast = try await fetchForecast() let air = try await fetchAirQuality() ``` `fetchAirQuality()` is not even called until `fetchForecast()` has returned. Nothing is blocked while this happens, because the thread is free during each suspension, but the screen still waits for the *sum* of both requests. That is correct when the second call needs the first call's result, such as fetching the air quality for the station the forecast names. For two independent requests it wastes time. The same is true of awaits in a loop: `for url in urls { try await load(url) }` loads one URL at a time, each starting only when the previous one has finished. ## What `async let` does `async let` binds a constant to an async call that starts **right away** and runs alongside the code that follows. Step by step: 1. `async let forecast = fetchForecast()` creates a **child task** of the current task and starts `fetchForecast()` in it. The parent does not suspend and needs no `await` on this line. 2. `async let air = fetchAirQuality()` starts a second child task the same way. 3. The parent runs any synchronous code that follows. 4. `try await (forecast, air)` suspends until both values are ready. Each read of an `async let` constant is a possible suspension point; `try` is needed because the initializers can throw. With two one-second requests, the sequential version takes about two seconds and the `async let` version about one. The children are part of **structured concurrency**: they belong to the parent task, they are cancelled when the parent task is cancelled, and they cannot outlive the scope that declared them. What happens when that scope exits before a child is awaited is a topic of its own. ## Rules the compiler enforces - **Async context only.** `async let` in a synchronous function is an error: `'async let' in a function that does not support concurrency`. - **`let` only.** `async var` is rejected: `'async' can only be used with 'let' declarations`. - **Local only.** A stored property such as `async let q = fetch()` inside a struct is rejected: `'async let' can only be used on local declarations`. - **Reads need `await`.** `let total = air + 1` is an error, `expression is 'async' but is not marked with 'await'`, because the value may not be ready yet. - **One run, many reads.** The initializer runs once. A second `await air` returns the same stored value without starting the work again, though it still needs the marker. - **No escaping.** Capturing an `async let` in an escaping closure fails with `capturing 'async let' variables is not supported`, because the child task cannot outlive its scope. - **Concurrent initializer.** The initializer runs concurrently with the parent, so the compiler's data-race checks apply to what it captures (covered in the lesson on Sendable). ## Choosing between them | Situation | Use | |---|---| | The second call needs the first call's result | sequential `await`s | | A fixed, small number of independent calls | `async let`, one per call | | A count known only at run time, such as fifty image URLs | a task group (covered in the lesson on tasks) | | Work that must keep running after the function returns | an unstructured `Task` (covered in the lesson on tasks) | `async let` keeps the call sites readable: each binding has its own name and its own type, so `forecast` stays a `Forecast` and `air` stays an `AirQuality`, with no result enum to unpack. A task group gives up that per-call typing in exchange for a dynamic number of children. ## Habits worth keeping - Start the independent calls first and do the synchronous setup after them, so the children run while the parent works. - Await each value as late as the code allows, at the point of use. - Read the values in an order that makes sense for errors: a tuple `try await (forecast, air)` waits for `forecast` before it looks at `air`. - Do not put an `async let` in front of a call whose result is needed on the very next line; that adds a child task and buys nothing. - Remember that every child task shares the same pool of threads and the same network as the rest of the app: two or three bindings are cheap, but they are not free.
- Does `async let forecast = fetchForecast()` suspend the parent function on that line?No. It starts a child task and returns at once, so the line needs no `await`. The parent suspends only where it reads `forecast`, and only if the child has not finished yet. That is why the call site of an `async let` reads like a plain `let`, while every use of the value carries `await`.
- Why can't you write `async var` to update the value later?The compiler rejects it with `'async' can only be used with 'let' declarations`. An `async let` is initialised once, by its child task; letting other code assign to it while that task runs would make its value and its initialisation ambiguous. Copy the awaited value into an ordinary `var` if you need to change it.
- When is a task group a better fit than `async let`?When the number of concurrent calls is only known at run time, such as one request per item in an array, or when you want results in completion order. `async let` declares one child per binding in source, so it fits a fixed handful of independent calls. Task groups are covered in the lesson on tasks.
- async let delays the call until the value is first awaited
- Two sequential awaits already run the two requests in parallel
- An async let line itself must be marked with await
- async let works in synchronous functions as long as the value is awaited later
- async var is allowed when the value needs updating later
- async let is always faster, even when the second call needs the first call's result