#90: Task Groups in Swift
Task groups are useful when the number of child tasks is dynamic.
let results = await withTaskGroup(of: Int.self, returning: [Int].self) { group in
for value in 1...3 {
group.addTask { value * 2 }
}
var collected: [Int] = []
for await result in group {
collected.append(result)
}
return collected
}
They let you fan out work, collect results as they finish and still keep everything scoped to the parent task.
If you have only two or three fixed child tasks, async let is often simpler.