The Power of Tasks in Swift: Concurrency Made Easy
Take it to the task!
--
Tasks are part of Swift’s new concurrency model introduced way back in 2021. Essentially a Task allows us to create a concurrent environment from a non-concurrent method. That is we can call async
APIs in order to perform work in the background giving us a safe way to manage concurrency.
Let’s look at the detail.
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 14.2, and Swift 5.7.2
Prerequisites:
- You will be expected to be aware of how to make a Single View Application
- Some familiarity with GCD and concurrency would be useful for the reader
Keywords and Terminology:
Task: A task represents a unit of work that can be executed asynchronously, independently of the main thread of the application.
What are Tasks in Swift?
Tasks are a unit of work that can be executed asynchronously, independently on the main thread of the application. That is, you can provide a closure that contains the work for the task to perform.
If you choose to give up a reference to your task you will be unable to wait for it to complete or to cancel it (more on that later).
A task produces a fresh execution context in which to run asyncronous code.
Which is a rather basic explanation. Perhaps this is better with a few examples? If you think you’re getting that if you read on you’d be right.
Key advantages of tasks
- They will be run in parallel (if it is safe to do so) with other tasks
- They work with async functions, and are capable of asynchronous execution
- Tasks have built-in support for cancellation which is useful if they are no longer needed or take too long to execute
- Swift’s concurrency model is designed to be performant, and Tasks are an integral part of this model