Contents

withTaskGroup(of:returning:isolation:body:)

Starts a new scope that can contain a dynamic number of child tasks.

Declaration

@backDeployed(before: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0)
func withTaskGroup<ChildTaskResult, GroupResult>(of childTaskResultType: ChildTaskResult.Type = ChildTaskResult.self, returning returnType: GroupResult.Type = GroupResult.self, isolation: isolated (any Actor)? = #isolation, body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult) async -> GroupResult where ChildTaskResult : Sendable

Discussion

A group always waits for all of its child tasks to complete before it returns. Even canceled tasks must run until completion before this function returns. Canceled child tasks cooperatively react to cancellation and attempt to return as early as possible. After this function returns, the task group is always empty.

To collect the results of the group’s child tasks, you can use a for-await-in loop:

var sum = 0
for await result in group {
    sum += result
}

If you need more control or only a few results, you can call next() directly:

guard let first = await group.next() else {
    group.cancelAll()
    return 0
}
let second = await group.next() ?? 0
group.cancelAll()
return first + second

Refer to TaskGroup documentation for detailed discussion of semantics shared between all task groups.

See Also

Tasks