Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 146 ยท Concurrency

Task Groups

Learn Swift task groups - withTaskGroup, addTask, collecting results in any order, withThrowingTaskGroup, cancelAll, limiting concurrency, discarding groups and the Swift 6 data-race rules.

async let is perfect when you know how many things you want to run side by side: two, three, maybe five, each with its own name. But real programs often have a list. Download every file in an array, check every URL a user pasted, resize every photo in a folder. You cannot write async let in a loop, because each async let needs its own variable. For work whose size is only known at run time, Swift gives you the task group.

A task group is a small scope that owns a number of child tasks. You add as many children as you like, collect their results as they finish, and leave the scope only when every child is done. This lesson shows the two group functions, how results come back, what happens when a child throws, how to limit how much runs at once, and which Swift 6 rules apply. It builds on async and await and Tasks.

Your first task group

withTaskGroup(of:) takes the type of value each child returns and a closure that receives the group. Inside, you call group.addTask { ... } once per piece of work, then read the results with for await.

Swift Squaring numbers in a task group

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.

Read this slowly, because every piece matters:

  1. of: Int.self says that each child task returns an Int. The type is part of the group, so all children must return the same type.
  2. addTask starts a child and returns immediately. The child begins to run right away, possibly in parallel with the loop that adds the others.
  3. for await value in group is an async sequence. It gives you each result when that child finishes, and the loop ends after the last child.
  4. The closure's return value becomes the value of the whole withTaskGroup call, so we await it into results.

The program prints [1, 4, 9, 16, 25] and then count: 5. I sorted the array on purpose: results arrive in completion order, not in the order you added the tasks. If the child for 3 happens to finish first, 9 comes out first. Never print or rely on the raw arrival order unless your design really does not care.

If you leave the closure without reading the results, the group still waits for every child before withTaskGroup returns. That is the structured part of structured concurrency: child tasks cannot outlive the scope that created them.

Keeping track of which result is which

Because results come back in any order, a bare Int often is not enough. You need to know which input produced it. The usual fix is to return a tuple (or a small struct) that carries the key along with the value.

Swift Returning key and value from each child

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.

Each child returns (String, Int), a document name and its count. The loop fills a dictionary, and printing sorted keys makes the output stable: body 5, intro 5, outro 3. Remember that a dictionary has no fixed order in Swift, so sort the keys before you print.

If you need the results in the original order of the inputs, return the index from each child and put the value into an array slot afterwards:

Swift Restoring the input order with indices

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 output is ["ALPHA!", "BETA!", "GAMMA!", "DELTA!"], in input order, no matter which child finished first. This "index and value" shape is the standard recipe for a parallel map.

Child tasks and Sendable

The closure you give to addTask runs concurrently with the code around it. Swift 6 therefore checks it for data races. A child may read constants and copy values, but it may not modify a variable that the surrounding code also uses. Here is what happens if you try to sum numbers by mutating a local variable from inside the children:

Swift Mutating a captured variable from a child (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.

This does not compile. The real message starts with main.swift:5:19: error: passing closure as a 'sending' parameter risks causing data races between code in the current task and concurrent execution of the closure, and the note under it says that the closure captures a reference to the mutable var total. Several children could update total at the same instant, which is a data race, and Swift 6 refuses to build code that has one. (Had total been a top-level variable of main.swift, the message would instead say that a main actor-isolated var cannot be mutated from a nonisolated context. Same problem, different wording.)

The fix is the pattern you already know: let each child return its value and combine the values in the one place that is safe, the loop that reads the group.

Swift Summing results in the collecting loop

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.

It prints 60. The sum variable lives in the closure body, which is not concurrent with the children, and only the for await loop touches it, one result at a time. The values the children return must be Sendable (safe to hand from one task to another), which Int, String and other value types made of such values are. The lesson on Sendable explains the rule in detail, and actors show how to share mutable state safely.

Groups that can throw

If a child can throw, use withThrowingTaskGroup(of:returning:body:). The group itself then throws, and you must write try in front of the call and in front of for try await.

Swift A throwing task group

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 child with id 3 throws. The for try await loop rethrows that error, which leaves the closure, and withThrowingTaskGroup throws it to the catch. The program prints group failed: invalid(3).

What about children 4 and 5, which were still sleeping? When the group's body exits with an error, Swift cancels all remaining children and waits for them to finish. Cancellation in Swift is cooperative: a child is told "please stop", and Task.sleep and other waiting functions react by throwing CancellationError. The group then discards those errors, because it already has the first one. You will see how to react to cancellation inside your own code in Cancellation and Timeouts.

Keeping the good results

Sometimes one failure should not ruin the batch. Catch the error inside the child and return a Result, an optional, or a value that says "failed":

Swift One failure does not stop the others

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.

Because each child converts its error into a Result, the plain non-throwing withTaskGroup is enough, and every name gets an answer. The final loop walks names in its original order, so the output order is stable. The Result type lesson covers this style in more depth.

Controlling the group by hand

The for await loop is the most common way to read a group, but the group has other tools:

Tool What it does
group.next() Waits for one more result; returns nil when no children are left
group.waitForAll() Waits for every child and ignores the results
group.cancelAll() Marks every child (and the group) as cancelled
group.isEmpty true when no child is running or waiting to be read
group.isCancelled true after cancelAll() or when the surrounding task is cancelled
group.addTaskUnlessCancelled Like addTask, but returns false and adds nothing if the group is cancelled

Using next() gives you "first result wins" behavior, such as asking three servers and taking the fastest answer:

Swift First result wins with next() and cancelAll()

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 output is answer from quick. After the first real answer arrives, cancelAll() makes the sleeping children throw CancellationError straight away, so the whole call finishes in about 10 ms instead of waiting 400. Note that next() returns String?? here (a result from the group, whose value is itself optional); the while let unwraps the outer layer and if let unwraps the inner one.

cancelAll() does not kill anything. It only sets a flag that children must check or notice (by calling Task.checkCancellation() or by awaiting something that throws on cancellation). A child that does a long loop of pure computation will keep running until it looks at the flag.

Limiting how many run at once

Adding a thousand children at once is legal and cheap, but every child may hold resources such as a network connection or a file handle. A common requirement is "at most N at the same time". The trick: start N children, then each time one finishes, start one more.

Swift A sliding window of at most three tasks

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.

At most three children exist at any moment. The program prints [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]. The variable next is mutated only by the body of the closure, never by a child, which is why Swift 6 accepts it. Notice that the child captures job, a fresh constant for each iteration, rather than reading jobs[next] itself.

Be aware that Swift also limits how many tasks actually run at once on its own thread pool, usually the number of CPU cores. A sliding window is about resources you consume while a task exists, not about CPU use.

Discarding task groups

If you never read the results (for example, you run a job for every client and each child handles its own work), a normal group still keeps every finished child's result around until you read it. A server that handles millions of requests would slowly leak memory. withDiscardingTaskGroup is the answer: its children return Void, results are discarded as soon as they finish, and the group takes no for await.

Swift withDiscardingTaskGroup

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 handled request lines may appear in any order, since the children run side by side. The last line always comes last, because the group waits for every child before returning. There is also withThrowingDiscardingTaskGroup. One difference is worth remembering: in a throwing discarding group, the first child that throws cancels all the others and the error is rethrown at once, without any reading code on your side.

Task groups versus the alternatives

You need Use
A fixed, small number of independent calls with names async let
A number of calls only known at run time withTaskGroup
The same, but children may throw withThrowingTaskGroup
Fire-and-forget children in long-lived servers withDiscardingTaskGroup
One piece of work that outlives the current scope An unstructured Task { } (Tasks)

Prefer a group over creating many unstructured Task { } values in a loop. A group guarantees that errors propagate, cancellation reaches every child, and nothing is left running when the function returns. With loose tasks you must build all of that yourself.

Common mistakes

  • Relying on completion order. The results of a group arrive in whatever order the children finish. Return keys or indices, or sort.
  • Mutating shared variables from children. Return values instead, and combine them in the collecting loop, as shown above.
  • Forgetting to read a throwing group. Errors surface only through for try await, next() or waitForAll(). A child that throws in a group nobody reads is ignored until the group scope ends.
  • Hiding a long computation from cancellation. A group can only ask children to stop. Check Task.isCancelled in long loops.
  • Adding work after the group scope. The group value is only valid inside its closure. Do not store it somewhere else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is a task group better than async let?

    async let needs a separate named variable for each child, so it only suits a fixed number of tasks. A task group lets you add children in a loop.
  2. 2. Child tasks in a withTaskGroup(of: Int.self) group return 1, 2 and 3. In which order does for await deliver them?

    Results arrive as children complete. To get a stable order, return an index or key with each result, or sort the collected values.
  3. 3. What does Swift 6 do when a child task modifies a local var declared outside the group?

    Swift 6 strict concurrency treats this as a possible data race and refuses to compile. Return values from children and combine them in the collecting loop.
  4. 4. In a withThrowingTaskGroup, one child throws while others are still running. What happens when the error leaves the group body?

    Leaving the body with an error cancels the remaining children, waits for them, and rethrows the first error. Cancellation is cooperative, so children must notice it.
  5. 5. What is withDiscardingTaskGroup for?

    A discarding group does not keep finished results around, which avoids memory growth in long-running programs that start huge numbers of children.

Summary

  • A task group (withTaskGroup, withThrowingTaskGroup) runs a run-time-sized set of child tasks and does not return until all of them are done.
  • Add children with addTask; read results with for await or next(). They arrive in completion order, so return a key or index (or sort) when order matters.
  • Children may not mutate captured variables in Swift 6. Return values and combine them in the loop that reads the group, and keep returned values Sendable.
  • In a throwing group, an error that leaves the body cancels the remaining children; catch inside a child and return a Result to keep partial results.
  • cancelAll() and isCancelled support first-result-wins designs, but cancellation is cooperative.
  • Limit concurrency with a sliding window: start N children, then add one each time next() returns.
  • withDiscardingTaskGroup suits fire-and-forget children whose results you never read.

Next: Actors shows how to protect mutable state that several tasks must share.