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.
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.
- by throwing an error.
- without throwing an error.
We can see these two flavours in the below Xcode’s auto complete suggestion screenshot.
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.
Task Group: Key Things to Keep in mind
- Each Task(Child Task) in a group must return the same type of data.
- Task Group needs a solid return type which it will return after processing the child task’s result.
- Each child Task should be able to run asynchronously and independently.
- There is no specific order in executing the child tasks.
- Task Group will wait for all its tasks to get it done.
- Task Group conforms to AsyncSequence protocol, hence we can extract the results for each child task by using group.next().
- 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.