Demystifying Swift’s Task() for Beginners: An Introduction to Asynchronous Programming.(Part-1)

Introduction

Vishwas Ng
MobilePeople
2 min readApr 13, 2024

--

Apple introduced async/await, concurrent support for the Swift language to handle processes like fetching data and executing long processes without disturbing the main thread. If you want to replace a traditional completion handler with a new async/await, first, you need to understand the importance of Task() and why it is important.

So, when a new API(or key) is introduced, like async/Await, Actors should know about the Task first.

Why to know about Task()?

If you start a new project or want to use asynchronous programming in an existing project, you create an async function and need to call that function from any of your existing non-async functions. If you ever try, that compiler will give an error as below.

'async' call in a function that does not support concurrency

What an error means is that you are trying to run/call an async from the context of the non-async process. How to fix it… bring/execute the function from the context of the async process and how to do it… YES, it's done by creating a task.

That’s why I first want to introduce you to ‘Task’. So, Before wasting any time, let's first look

What is Task()?

Task is a simple API that helps run asynchronous code within an iOS application. It helps you run asynchronous code from a place/Context that an asynchronous execution code doesn't support.

For example:- you want to run async code from any lifecycle of the ViewController or Any action block within SwiftUI.

when using async code in the above places Task comes in handy.

How to create Task()?

The task can be simplified as simply as the code snippet

Task {
// do some async stuff
}

So you learned what a task is, why it's needed, and how to create it. Now let's move on to the next part i.e. Part 2. How tasks work and different flavors of Tasks.

--

--