Modern Concurrency with async/await in Swift(Task). Part — 2.

In this article, we will learn Tasks

Rahul Patel
Globant
2 min readApr 1, 2022

--

Please read part 1 first, If you have not already.
https://medium.com/@rahul.patel_41877/modern-concurrency-with-async-await-in-swift-part-1-2e4ee3272cc8

Let's understand the Task

Types of Tasks

  1. Task (unstructured)
  2. Async-let Tasks / Async-let binding (structured)
  3. Group Tasks (structured)
  4. Detached Tasks (unstructured)

Task

We can use Task to call an async function anywhere. We also specify the priority for the operation.

If you try to run this in the playground don’t forget to add the below code

Async-let Task / Async-let binding

This will allow a developer to create an async variable, which value will be assigned from the async function.
While using this variable we must need to write await, as those variables are computed from the async function

Group Task

A task group is for concurrency with dynamic width, one must use this while calling multiple async tasks.
We can achieve this with a function called withTaskGroup
While achieving multiple async calls, we also need to take care of data races, which can lead to crashes sometimes.
Here AsyncSequence comes into the picture as a group has confirmed to AsyncSequence protocol to loop through.
That will help you to iterate elements as they are available. That’s why we write await keyword before the variable in For Await loop

Detached Task

The detached task is a bit different from the normal Task. In structured Tasks, the operation uses structured concurrency features like child tasks. Child tasks inherit the parent task’s priority and task-local storage, and cancelling a parent task automatically cancels all of its child tasks. You need to handle these considerations manually with a detached task.

For in-depth knowledge of Structure concurrency & Tasks watch this WWDC video
https://developer.apple.com/videos/play/wwdc2021/10134/

--

--