<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/withTaskGroup(of:returning:isolation:body:)",
  "metadataVersion" : "0.1.0",
  "role" : "Function",
  "symbol" : {
    "kind" : "Function",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:12_Concurrency13withTaskGroup2of9returning9isolation4bodyq_xm_q_mScA_pSgYiq_ScGyxGzYaXEtYas8SendableRzr0_lF"
  },
  "title" : "withTaskGroup(of:returning:isolation:body:)"
}
-->

# withTaskGroup(of:returning:isolation:body:)

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

```
@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/Swift/TaskGroup) documentation for detailed discussion of semantics shared between all task groups.

> SeeAlso: ``doc://com.apple.Swift/documentation/Swift/TaskGroup``

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)