The Analogy: The General Contractor and Subcontractors
On a well-run building site, a general contractor manages one phase at a time and never works alone. When the framing phase begins, the contractor dispatches subcontractors -- a plumber, an electrician, a roofer -- each to their own job, and the site's ironclad rule is that no subcontractor may still be working when the phase is signed off. The contractor cannot close the phase until every sub they dispatched has reported back or been sent home. That rule, that dispatched work is bounded by the phase that started it, is structured concurrency: a parent task starts child tasks, and the children can never outlive the scope that created them.
Sending several subs off at once is how the site saves time. The moment the contractor writes three work orders and hands them out, the plumber, electrician, and roofer all begin simultaneously, and the framing phase takes as long as the slowest of them rather than the three added together. Writing those simultaneous orders is async let. Later, when the contractor needs a specific result before continuing -- the wiring must be inspected before the walls close -- they stop at the inspection point and wait for that sub to finish. Stopping to wait for a result is await: a suspension point where the contractor pauses this thread of work, free to attend to other things, until the awaited job is done.
Some equipment cannot be shared carelessly. There is one cement mixer with one operator, and only one worker may use it at a time; anyone who needs it queues and waits their turn, which keeps its half-mixed batch from being ruined by two people dumping in at once. That single-operator mixer is an actor: it protects its internal state by serialising access, so every request to use it must wait for the mixer to be free. And on a day when the contractor does not know in advance how many identical units are needed -- twelve window frames, or however many the drawings call for -- they hand out work orders dynamically and collect each finished frame as it comes back. That open-ended batch of identical child jobs is a task group.
The danger on this site is the off-the-books subcontractor: one hired outside the phase structure who keeps working after the phase is closed and the contractor has gone home. Nobody waits for this worker, nobody inspects their output, and if the client cancels the whole project, no message reaches them, so they keep pouring concrete into a foundation that is already being demolished. That is an unstructured, detached task. Work spawned outside the parent's scope escapes every guarantee structured concurrency provides -- the parent will not wait for it, errors it raises are not propagated back, and cancellation never reaches it. The convenience of "just start it and forget it" is exactly how a site ends up with orphaned work running against a job that no longer exists.
Syntax or Core Structure
An asynchronous function is marked with async, and every call to one is marked with await at the point where the caller may suspend. The await does not mean "block the thread"; it means "this thread of work pauses here and may be resumed later, and while it waits the underlying thread is free to run other work."
// Declaring and calling an async function
func loadCount() async -> Int {
return 42
}
let count = await loadCount() // await marks the suspension point
To run several independent jobs at the same time, bind them with async let. Each binding starts its work immediately; you await the bindings later to read the results. If any job can fail, add throws to the functions and try to the awaits.
async let a = loadCount() // starts now
async let b = loadCount() // starts now, alongside a
let sum = await a + (await b) // wait for both, then combine
An actor protects mutable state: its stored properties are isolated, and every access from outside is asynchronous, so callers must await. A task group runs a dynamic number of identical child jobs and collects their results as they complete.
actor Tally {
private var total = 0
func add(_ n: Int) { total += n }
func value() -> Int { total }
}
await withTaskGroup(of: Int.self) { group in
for n in [1, 2, 3] { group.addTask { n * n } }
for await square in group { print(square) } // completion order
}
Technical Depth: How Swift Runs Work Concurrently
await marks a suspension point, not a blocked thread
When you call an async function with await, the calling task may suspend: it hands its thread back to the system, and resumes when the awaited work is ready. Nothing after the await runs until the result arrives, so within a single function the statements still execute top to bottom in the order you wrote them. Concurrency comes from starting other work before you await, not from the await itself.
func doubled(_ n: Int) async -> Int {
return n * 2
}
func summary() async {
let a = await doubled(10) // suspends until doubled returns 20
let b = await doubled(a) // then suspends again; b depends on a
print("a = \(a)")
print("b = \(b)")
}
await summary()
Output:
a = 20
b = 40
Because b is computed from a, these two calls must run one after another; await is exactly the tool that expresses "I need this result before I go on."
| Aspect | Ordinary call | await call |
|---|---|---|
| Marked with | nothing | await |
| May suspend the caller | no | yes, at the await |
| Allowed inside | any function | an async function or a Task |
async let starts children in parallel
When two jobs do not depend on each other, async let starts them both at once. The bindings begin their work immediately; you pay the wait only when you await them. The result does not depend on which child finishes first.
func cube(_ n: Int) async -> Int {
return n * n * n
}
func totals() async {
async let x = cube(2) // all three start
async let y = cube(3) // immediately, together
async let z = cube(4)
let sx = await x
let sy = await y
let sz = await z
print("x = \(sx)")
print("total = \(sx + sy + sz)")
}
await totals()
Output:
x = 8
total = 99
The three cubes (8, 27, 64) may complete in any order, but the printed total is always 99 because addition does not care about order. Wall-clock time is the slowest single cube, not the sum of all three.
Actors serialise access to shared state
An actor is like a class whose mutable state can be touched by only one task at a time. The compiler enforces this: from outside the actor, every property read and method call is asynchronous, so you must await. Two tasks calling add at the same moment cannot interleave and corrupt the running total; the actor processes them one after another.
actor Counter {
private var value = 0
func add(_ n: Int) {
value += n
}
func current() -> Int {
return value
}
}
func runCounter() async {
let counter = Counter()
await counter.add(5)
await counter.add(3)
let total = await counter.current()
print("total = \(total)")
}
await runCounter()
Output:
total = 8
| Aspect | class | actor |
|---|---|---|
| Shared mutable state across tasks | data-race risk | serialised, safe |
| Access from outside | direct | via await |
| Safety enforced by | nothing | the compiler |
Task groups fan out a dynamic number of jobs
A task group runs as many child tasks as you add, then lets you collect results with for await. The catch for a determinism-minded author: results arrive in completion order, which is not predictable. If you append them to an array and print that array, the order is a coin toss. So combine results in an order-independent way -- sum them, count them, or sort before printing.
func lengthOf(_ word: String) async -> Int {
return word.count
}
func totalLength(of words: [String]) async -> Int {
return await withTaskGroup(of: Int.self) { group in
for word in words {
group.addTask { await lengthOf(word) }
}
var sum = 0
for await length in group {
sum += length // order-independent
}
return sum
}
}
let words = ["swift", "async", "actor"]
let total = await totalLength(of: words)
print("word count = \(words.count)")
print("total length = \(total)")
Output:
word count = 3
total length = 15
Each word here is five letters, so the total is 15 no matter which child reports first. Had the code appended lengths to an array and printed [5, 5, 5] for three different words, the values would be right but their positions unreliable -- summing sidesteps the problem entirely.
Real World Example: A Parallel Quote Aggregator
A price-comparison feature asks several vendors for a quote on the same item and shows the cheapest. The vendor lookups are independent, so there is no reason to ask them one at a time; async let fires all three at once and the feature waits only as long as the slowest single vendor. Each lookup below is a pure stand-in for a network call so the output can be traced exactly.
struct Quote {
let vendor: String
let cents: Int
}
func priceFromAcme(_ sku: String) async -> Quote {
return Quote(vendor: "Acme", cents: 1299)
}
func priceFromBolt(_ sku: String) async -> Quote {
return Quote(vendor: "Bolt", cents: 1180)
}
func priceFromCrest(_ sku: String) async -> Quote {
return Quote(vendor: "Crest", cents: 1245)
}
func bestQuote(for sku: String) async -> Quote {
async let a = priceFromAcme(sku)
async let b = priceFromBolt(sku)
async let c = priceFromCrest(sku)
let quotes = [await a, await b, await c]
var best = quotes[0]
for q in quotes.dropFirst() {
if q.cents < best.cents {
best = q
}
}
return best
}
func dollars(_ cents: Int) -> String {
let d = cents / 100
let c = cents % 100
let padded = c < 10 ? "0\(c)" : "\(c)"
return "$\(d).\(padded)"
}
let winner = await bestQuote(for: "SKU-42")
print("checked 3 vendors")
print("best: \(winner.vendor) at \(dollars(winner.cents))")
Output:
checked 3 vendors
best: Bolt at $11.80
The three async let bindings launch the moment they are declared, so all three vendors are queried concurrently. Building the quotes array by awaiting a, b, then c in a fixed order gives the array a stable shape regardless of which vendor actually answered first, which is what keeps the trace deterministic. The scan then walks the array once, holding onto the lowest cents seen: Acme at 1299 is the starting best, Bolt at 1180 undercuts it, and Crest at 1245 does not, so Bolt wins and dollars renders 1180 cents as $11.80.
The concurrency here is genuine and correct: the feature costs one vendor's latency instead of three added together, and because the reduction (finding the minimum) is order-independent, the answer never depends on completion order. This is the everyday shape of async let -- a fixed, small set of independent jobs whose results you combine once they are all in.
The structured scope also means the caller cannot leave a query running loose. When bestQuote returns, all three child tasks have completed; nothing escapes into the background to finish unwatched. That guarantee is the whole point of doing this work with async let inside one function rather than spawning three detached tasks and hoping they land.
The design flaw is that bestQuote waits for every vendor before it answers, with no timeout and no cancellation. If Crest were a real endpoint that hung, await c would block the result forever even though Bolt's cheaper quote is already in hand -- the code needs the slowest vendor even when it does not need that vendor's number. The fixed three-async let shape also cannot grow: a real system with a vendor list of unknown length would need withTaskGroup over that array. A production version would run the lookups in a throwing task group with a per-vendor deadline, reduce to the minimum as results arrive, and treat a vendor that misses its deadline as simply absent rather than a reason to stall the whole comparison.
Common Mistakes
- Awaiting in sequence when the work is independent. Writing
let a = await first(); let b = await second()runs the two calls back to back even though neither needs the other. If they are independent, bind them withasync letso they overlap; sequentialawaitthrows away the parallelism concurrency exists to give you.
- Thinking await blocks the thread.
awaitsuspends the current task and frees the thread for other work; it is not a thread-blocking wait. Treating it like a blocking sleep leads people to fear using it and to reach for raw threads or locks that the concurrency model already handles.
- Reading actor state and assuming it is unchanged after an await. An actor guarantees one-at-a-time access, but across a suspension point inside an actor method other tasks may run and mutate its state (actor reentrancy). Caching a value before an
awaitand trusting it afterwards can be wrong.
- Printing task-group results and expecting a fixed order.
for awaityields results in completion order, which is not deterministic. Code that appends to an array and relies on the positions will pass sometimes and fail other times. Sort, or combine in an order-independent way, before you depend on order.
- Spawning detached tasks to "fire and forget".
Task.detachedescapes the structured scope: the parent will not wait for it, its errors are not propagated, and cancellation does not reach it. This is how work leaks and keeps running against state that no longer exists.
- Forgetting that a child task inherits cancellation. Inside a structured task, long work should check
Task.isCancelledor calltry Task.checkCancellation(). Code that never checks keeps running after the parent is cancelled, wasting the very time cancellation was meant to save.
- Marking a function async when nothing in it suspends. Adding
asyncto a function that does no awaiting forces every caller toawaitfor no reason and spreads asynchrony through the codebase. Make a function async only when it actually awaits something.
- Sharing a plain class across tasks instead of an actor. A regular class with mutable state read and written from several tasks is a data race, which is undefined behaviour. If the state is shared and mutable, protect it with an actor (or make the type immutable) rather than hoping the timing works out.
- Calling a blocking API inside an async function. A synchronous call that blocks (a long
sleep, blocking file or socket I/O) ties up a thread from the cooperative pool and can stall other tasks. Use the async equivalent, or move the blocking work off the pool, so the thread stays available.
Best Practices
- Prefer structured concurrency over detached tasks. Keep child work inside
async letor a task group so the parent waits for it, errors flow back, and cancellation propagates. Reach forTask.detachedonly when you genuinely need work untied from the current context, and then own its lifetime deliberately.
- Use async let for a fixed, small set of independent jobs. When you know exactly which few things to run in parallel and will combine them once,
async letreads clearly and finishes when the slowest one does. Save task groups for when the number of jobs is dynamic.
- Use a task group when the number of jobs is data-driven. If you are launching one child per element of a collection,
withTaskGroup(orwithThrowingTaskGroup) expresses it directly and bounds all the children to the group's scope.
- Combine task-group results in an order-independent way. Sum, count, reduce, or sort before you rely on ordering, because results arrive as they finish. Never assume the first result out is the first task you added.
- Protect shared mutable state with an actor. If more than one task can touch the same mutable data, an actor removes the data race by construction and the compiler checks it. Immutable data needs no protection and can be shared freely.
- Check for cancellation in long-running work. Call
try Task.checkCancellation()or testTask.isCancelledat natural break points in loops and long computations so a cancelled task stops promptly instead of finishing work no one wants.
- Add async only where a function truly suspends. Let asynchrony follow the actual awaits rather than painting it across functions that merely call async code without needing to. This keeps the async surface of your code honest and small.
- Give concurrent work deadlines instead of waiting forever. Wrap remote or open-ended calls with a timeout so one slow participant cannot stall the whole operation, and treat a missed deadline as a handled outcome rather than an indefinite hang.
Practice Exercises
- Sequential to parallel: Start with a function that awaits three independent lookups one after another and returns their sum. Rewrite it using
async letso all three run concurrently, and confirm the returned sum is unchanged while the code now waits only for the slowest lookup.
- A safe counter actor: Write an
actorthat holds a running total withadd(_:)andvalue()methods. From an async function, calladdseveral times withawait, then printvalue(). Explain why the same code written as a plain class with a shared instance would risk a data race.
- Deterministic task-group total: Use
withTaskGroupto launch one child per element of[3, 1, 4, 1, 5], each returning that number squared. Collect the results and print their sum. State why summing is safe here even though the children finish in an unpredictable order, and what would break if you printed the raw collected array instead.
- Cancellation-aware work: Write an async function that loops many times doing a small piece of work and calls
try Task.checkCancellation()each pass. Describe what happens to that function when the surrounding task is cancelled, and contrast it with the same work started as a detached task that never checks cancellation.