A Swift `headline(compact:)` function starts `async let air` and returns early without awaiting it; why does that return still take two seconds?
answer
- no child outlives its scope
- implicit cancel, then implicit await
- cancellation is only a flag
- a busy loop never looks
- unawaited errors are dropped
basics
~20 sAn async let child task cannot outlive its scope. On the early return Swift cancels the unawaited child and then waits for it to finish; cancellation is cooperative, so a child that never checks it runs its full two seconds.
solid answer
~50 s`async let` is structured: when the scope that declared it exits, by `return`, by a thrown error or by falling off the end, Swift implicitly **cancels** every child it has not awaited and then implicitly **awaits** it. Cancellation only sets a flag on the child task. A child that suspends in `Task.sleep(for:)` or checks `Task.isCancelled` stops quickly; a child doing busy work that never checks keeps running, and the early return waits for all of it. The child's result, or its error, is then thrown away. Fixes: declare the `async let` only on the path that uses it, make the child check for cancellation (covered in the lesson on cancellation), or, when the work truly must outlive the function, start an unstructured task instead. The same wait hides in `try await (forecast, air)`: an error from `air` surfaces only after `forecast` has finished.
code
swift · 30 linesstruct AirQuality: Sendable { let index: Int }
// Busy work with no suspension point and no cancellation check.
func computeAirQuality() async -> AirQuality {
let clock = ContinuousClock()
let deadline = clock.now + .seconds(2)
while clock.now < deadline { }
return AirQuality(index: 42)
}
func fetchForecast() async throws -> String {
try await Task.sleep(for: .milliseconds(100))
return "Sunny"
}
func headline(compact: Bool) async throws -> String {
async let air = computeAirQuality()
let forecast = try await fetchForecast()
if compact { return forecast } // air is cancelled, then awaited, before this returns
return "\(forecast), AQI \((await air).index)"
}
@main struct Main {
static func main() async throws {
let clock = ContinuousClock()
let start = clock.now
let text = try await headline(compact: true)
print(text, clock.now - start) // Sunny 2.0… seconds
}
}go deeper
Recall that an async let child cannot outlive the function that started it.
Explain the implicit cancel-then-await at scope exit and why a child that ignores cancellation delays the return.
Diagnose slow early returns and swallowed errors from unawaited async let children, and restructure so children start only where they are used.
Decide where a codebase wants structured children versus deliberately unstructured work, and make cancellation-aware APIs the team's default.
## The rule: every `async let` is awaited before its scope ends An `async let` binding starts a **child task** that belongs to the current task and to the scope that declared it. Swift Evolution's `async let` proposal is explicit: a binding that was declared but never awaited explicitly is awaited *implicitly* as its scope exits, and it is *cancelled* first. That is the price of **structured concurrency**: no child can still be running after the function that started it has returned, so no work leaks past the code that owns it. The alternative, abandoning the child, would leave work running that nobody will ever read, possibly touching state after its owner has gone. Waiting keeps task lifetimes nested the way local variables are. ## Tracing `headline(compact: true)` In the example below, `computeAirQuality()` spins for two seconds without ever suspending. 1. `async let air = computeAirQuality()` starts the child task, which begins its loop. 2. `try await fetchForecast()` suspends the parent for about 100 ms and returns `"Sunny"`. 3. `compact` is `true`, so `return forecast` runs. 4. Before the function can return, Swift marks `air`'s child task as cancelled. 5. Swift then awaits the child. Its loop never looks at the cancellation flag, so it runs until the two seconds are up. 6. The child's `AirQuality` value is thrown away, and `headline(compact:)` finally returns. The measured result is about 2.0 seconds for a function whose own work took 0.1. ## Cancellation only sets a flag Swift's cancellation is **cooperative**. Cancelling a task does not stop it; it records that the task is cancelled, and the task's own code decides what to do. In practice: - a child suspended in `try await Task.sleep(for:)` is woken and the call throws, so the child finishes almost at once; - a child that checks `Task.isCancelled` or calls `try Task.checkCancellation()` in its loop can stop early; - a child in a synchronous loop, a blocking call or an SDK call that ignores cancellation keeps going, and the parent waits for it. When the child above is replaced with one that sleeps through `Task.sleep(for:)`, the same early return takes well under a millisecond. The APIs for checking cancellation are covered in the lesson on tasks and cancellation; what belongs here is that an unawaited `async let` is the thing that triggers it. ## Every exit waits | How the scope exits | What happens to unawaited `async let` children | |---|---| | an early `return` | cancelled, then awaited; results discarded | | a thrown error | cancelled, then awaited, then the error propagates | | `async let _ = work()` reaching the end of scope | cancelled, then awaited, like any unused binding | | the end of the scope with every value awaited | nothing left to do | Two consequences surprise people: - **Errors vanish.** If an unawaited child's initializer throws, its error is dropped and the function returns normally. A failure you never await is a failure you never see. - **Tuple order matters.** `try await (forecast, air)` awaits `forecast` first. If `air` throws after 10 ms while `forecast` takes two seconds, the caller sees `air`'s error after about two seconds, and nothing cancels `forecast` in the meantime, because nobody has looked at `air` yet. A task group that handles results in completion order fixes this (covered in the lesson on tasks). ## Fixing the slow early return 1. **Start the child only where it is used.** Move `async let air` inside the branch that reads it, so the compact path never creates it. 2. **Make the child cooperative.** Have long loops check `Task.isCancelled`, and prefer APIs that suspend over ones that block. 3. **Await what you start.** If both paths need the value, await it on both, and handle its error. 4. **Use an unstructured task only on purpose.** If the work really should finish after the function returns, such as warming a cache, that is a `Task { }` with its own lifetime (covered in the lesson on tasks), not an `async let`. An `async let` is a promise that the work ends with the scope. When a function returns slowly for no visible reason, look for a child it started and never needed. A quick test is to time the function on each exit path: a path that returns after the slowest child's duration, even though it never reads that child, has an unawaited `async let` behind it.
- If the unawaited `async let` child had been suspended in `Task.sleep(for:)`, how long would the early return take?Almost no time. The implicit cancellation wakes the sleep, `Task.sleep(for:)` throws, the child finishes, and the implicit await completes at once. Measured, the same early return drops from about two seconds to well under a millisecond. The wait is only as long as the child takes to notice cancellation.
- What happens to an error thrown by an `async let` child that the function never awaits?It is discarded. The child is cancelled and awaited when the scope exits, but its result, value or error, is thrown away, and the function returns normally. If the failure matters, await the value and handle the error explicitly.
- Why might `try await (forecast, air)` report `air`'s quick failure late?The tuple reads its elements in order, so it waits for `forecast` before it looks at `air`. While `forecast` runs, `air` has already failed, but nobody has observed it, so nothing cancels `forecast`. The error surfaces only once `forecast` completes. Handling results in completion order needs a task group.
- An unawaited async let child keeps running after the function returns
- Returning early stops an async let child immediately
- Cancelling a task forcibly stops whatever code it is running
- The compiler rejects an async let that is never awaited
- An error from an unawaited async let is rethrown when the function returns
- try await (a, b) reports b's error as soon as b fails