TaskGroup for parallelism
Use withTaskGroup to run parallel child tasks, iterate results as they arrive, and handle failures with the throwing variant.
TaskGroup for parallelism is a free Swift Academy lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why TaskGroup?
TaskGroup launches many child tasks in parallel and collects results safely. The group finishes only when all children complete.
- Spawn with group.addTask
- Consume with for await
- Use the throwing variant for error propagation
Spawn & collect
Spawn children with addTask and iterate results as they arrive using for await.
func work(_ n: Int) async -> Int {
try? await Task.sleep(nanoseconds: UInt64(50_000_000 * n)) // simulate delay
return n * n
}
Task {
let result = await withTaskGroup(of: Int.self) { group in
for i in 1...4 {
group.addTask { await work(i) } // spawn child
}
var sum = 0
for await value in group { // values as they finish
sum += value
}
return sum
}
print("sum =", result) // 1^2+2^2+3^2+4^2 = 30
}Aggregate results
A group is an async sequence of results; reduce or loop to build a single return value.
func sumSquares(_ n: Int) async -> Int {
await withTaskGroup(of: Int.self) { group in
(1...n).forEach { i in
group.addTask { await work(i) }
}
return await group.reduce(0, +) // reduce over async sequence
}
}
Task {
print(await sumSquares(5)) // 55
}Throwing groups
Use withThrowingTaskGroup to propagate the first error; cancel remaining children to stop wasted work.
enum CalcError: Error { case boom(Int) }
func risky(_ i: Int) async throws -> Int {
try await Task.sleep(nanoseconds: 30_000_000)
if i == 3 { throw CalcError.boom(i) }
return i
}
Task {
do {
let total = try await withThrowingTaskGroup(of: Int.self) { group in
for i in 1...5 { group.addTask { try await risky(i) } }
var sum = 0
do {
for try await v in group { sum += v }
return sum
} catch {
// Cancel remaining children on error
group.cancelAll()
throw error
}
}
print("total:", total)
} catch {
print("failed:", error) // boom(3)
}
}Cancel children
Call group.cancelAll() to request cancellation. Children should check Task.isCancelled (or Task.checkCancellation()) and exit quickly.
func slow(_ i: Int) async -> Int {
for _ in 0..<5 {
if Task.isCancelled { return -1 } // observe cancellation cooperatively
try? await Task.sleep(nanoseconds: 20_000_000)
}
return i * 10
}
Task {
let value = await withTaskGroup(of: Int.self) { group in
for i in 1...3 { group.addTask { await slow(i) } }
// cancel quickly (e.g., user navigated away)
group.cancelAll()
// Still need to drain results; cancelled children should exit fast
var out = 0
for await v in group { out += v }
return out
}
print("after cancel, collected:", value)
}Guidelines
Tips:
- Prefer task groups when the number of children is dynamic.
- Use the throwing variant for fail-fast behavior.
- Always drain the group (loop results) even after cancel.
- Keep child tasks small so cancellation is responsive.
Structured join semantics
Quick check: What is guaranteed by withTaskGroup?
Recap
Recap: Use withTaskGroup to spawn parallel work, iterate results as they arrive, and prefer the throwing variant to fail fast and cancel the rest.
Frequently asked questions
Is the “TaskGroup for parallelism” lesson free?
Yes — the full text of “TaskGroup for parallelism” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “TaskGroup for parallelism”?
Use withTaskGroup to run parallel child tasks, iterate results as they arrive, and handle failures with the throwing variant. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “TaskGroup for parallelism” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- TaskGroup for parallelism
- Actors & data isolation, nonisolated
- Sendable and thread-safety checking