Generic Function

withTaskGroup(of:returning:body:)

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

Declaration 宣言

func withTaskGroup<ChildTaskResult, GroupResult>(of childTaskResultType: ChildTaskResult.Type, returning returnType: GroupResult.Type = GroupResult.self, body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult) async -> GroupResult where ChildTaskResult : Sendable

Discussion 解説

A group waits for all of its child tasks to complete or be canceled before it returns. 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

Task Group Cancellation タスクグループ取り消し

You can cancel a task group and all of its child tasks by calling the cancellAll() method on the task group, or by canceling the task in which the group is running.

If you call async(priority:operation:) to create a new task in a canceled group, that task is immediately canceled after creation. あなたがasync(priority:operation:)を呼び出すことで新しいタスクをある取り消されたグループの中に作成するならば、そのタスクは作成の後に直ぐに取り消されます。 Alternatively, you can call asyncUnlessCancelled(priority:operation:), which doesn’t create the task if the group has already been canceled Choosing between these two functions lets you control how to react to cancellation within a group: some child tasks need to run regardless of cancellation, but other tasks are better not even being created when you know they can’t produce useful results.

Because the tasks you add to a group with this method are nonthrowing, those tasks can’t respond to cancellation by throwing CancellationError. The tasks must handle cancellation in some other way, such as returning the work completed so far, returning an empty result, or returning nil. For tasks that need to handle cancellation by throwing an error, use the withThrowingTaskGroup(of:returning:body:) method instead. あなたがグループにこのメソッドで加えるタスクはスローしないことから、それらタスクは、CancellationErrorをスローすることによって取り消しに応答できません。タスクは取り消しを何らかの他の方法で取り扱わなければなりません、たとえばそれまでに完了された仕事を返す、空の結果を返す、またはnilを返すなど。エラーをスローすることによって取り消しを取り扱う必要があるタスクのために、withThrowingTaskGroup(of:returning:body:)メソッドを代わりに使ってください。