Task Group in Swift

As Apple introduced new Swift Concurrency program from Swift 5.5, Task group in Swift is an another gem in the diamond ring. A Task Group is a collection of concurrent tasks which runs asynchronously and returns the same type of result.

devCracker
2 min readNov 30, 2021
Task Group in Swift — Handling multiple tasks in Swift
Photo by "My Life Through A Lens" on Unsplash

If you are an iOS developer for quite long time, to handle multiple async tasks, you have been using DispatchQueue and DispatchGroup so far. Task Group in Swift introduced by Apple as part of latest Swift Concurrency concept, makes our life easier for this kind of use cases.

In this article, we will learn Task Group by knowing its types and limitations.

Task Group in Swift helps us executing the parallel or concurrent tasks and groups its result to return as a single final output.

Creating a Task Group:

Task Group creation comes in two different cases for us.

  1. by throwing an error.
  2. without throwing an error.

We can see these two flavours in the below Xcode’s auto complete suggestion screenshot.

Different ways of creating a Task Group. 1. withTaskGroup 2.withThrowingTaskGroup
Different ways of creating a Task Group.

Let’s understand the Swift’s Task Group creation with following example. Assume that we need to get list of mutual friends and unfortunately iOS app need to make an individual API call to get all the mutual friend details.

Creating Swift’s Task Group

Task Group: Key Things to Keep in mind

  1. Each Task(Child Task) in a group must return the same type of data.
  2. Task Group needs a solid return type which it will return after processing the child task’s result.
  3. Each child Task should be able to run asynchronously and independently.
  4. There is no specific order in executing the child tasks.
  5. Task Group will wait for all its tasks to get it done.
  6. Task Group conforms to AsyncSequence protocol, hence we can extract the results for each child task by using group.next().
  7. addTask() helps to add a new Task in the group.

Tip: I would encourage you to read async await, Task and AsyncSequence to learn more about Swift’s new Concurrency programming.

Upgrade your medium membership from here to read good amount of article and scale your skills.

--

--

devCracker

professional mobile app developer | iOS | Android | GraphQL | Typescript | nodejs. Sports and musics fuels my mind to get back to development