0Pricing
Swift Academy · Lesson

TaskGroup for parallelism

Use withTaskGroup to run parallel child tasks, iterate results as they arrive, and handle failures with the throwing variant.

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
}

All lessons in this course

  1. TaskGroup for parallelism
  2. Actors & data isolation, nonisolated
  3. Sendable and thread-safety checking
← Back to Swift Academy