Understanding Task in Swift

This simple use case will help you to learn Swift’s latest addition called “Task” in concurrency programming.

devCracker
3 min readNov 6, 2021
Walking through Swift’s Task in few min
Photo by Anastasia Zhenina on Unsplash

This article would walk you through Swift’s Task, which is introduced in WWDC 2021 by Apple. Before going further into this, I would suggest you to have a quick on understanding of Swift’s async await, if you are not aware of that already.

Swift Task helps us to make the asynchronous operation in a synchronous method.

Let’s take a small use case to understand Task in Swift.

We suppose to get the User details and Orders associated with that particular user, for our learning purpose, User details and list of orders both are coming from different API routes. Application side, we need to map orders to User model.

Without using Swift Task:

Below is the high level code which does our job without using Task. To parse the data, we would need these two decodable structs.

struct User: Decodable {let id: Stringlet phone: String}extension User {func orders(from orders: [Order]) -> [Order] {orders.filter({ $0.userId == id })}}struct Order: Decodable {let id: Stringlet productName: Stringlet quantity: Intlet price: Floatlet userId: String}

And to get the data we would need some skeleton method like this.

func fetchUserDetailsAndOrders() { // completion block needs to be here to handle asynchronus operationvar user: User?var orders: [Order]?if let url = URL(string: “api route to get user details”) {let userTask = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, response, error inguard let data = data else {return}user = try? JSONDecoder().decode(User.self, from: data)}.resume()}if let url = URL(string: “api route to get order list”) {let orderTask = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, response, error inguard let data = data else {return}orders = try? JSONDecoder().decode([Order].self, from: data)}.resume()}
//logic has to be done to handle completion and pass the data.
}

So, if we take a look on the above skeleton code, we have to take care of asynchronous operations by utilising completion blocks. This completion block needs to be called from various use cases, be it successful response or error response on both API responses. This would have some boilerplate code and chances of writing too many code for this job.

Swift Task makes our life easier from Swift 5.5 onwards, let’s see how it is going to be simple and clean with Task.

Using Swift Task:

Our models User and Order are going to remain same, main change will be in our async method(fetchUserDetailsAndOrders).

We would need two Tasks and we will get the value from those two Tasks without any completion block, just by using await and value keywords.

func fetchUserDetailsAndOrders() async {let userTask = Task { () -> User in// getting user data from server}let orderTask = Task { () -> [Order] in//getting list of orders}do {let user = await try userTask.valuelet orders = await try orderTask.valuelet userOrders = user.orders(from: orders)print(“user orders \(userOrders)”)} catch let error {print(“error: \(error.localizedDescription)”)}}

Now, our code looks simple and easy to read, correct?

Key points in Swift Task:

  1. Task starts running automatically as soon as we initialise it, no separate method as resume() or start()
  2. task.value helps to get the value from Swift Task.
  3. await keyword requires here to get the value, as Task will be on different thread from the moment it gets initialised.
  4. Task can be used without returning the value or result like fire and forget concept.

Thats all for now about Swift Task. I hope, this high-level write up might have helped you to get the basic knowledge on Swift Task.

What’s next?

Okay, So far we have gone through about single Task, Swift provides an another concept called Task group which helps us to manage the list of task. Please click here to read about task group.

Other latest Swift concepts like Async/Await, Actors, @MainActor in Swift are interesting one to use and shape your Swift programming skills.

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

--

--

devCracker
devCracker

Written by devCracker

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