4th Jan 2022

Concurrency in Swift: async/await

Mobile App

Written By, Abhishek Bakhai

Overview

In the past, we followed the concurrency basics of code in swift using libraries like Grand Central Dispatch (GCD) or libdispatch.

Nowadays, we can enforce the basics for concurrency using the async and await keywords.

1. What is Concurrency?

Let’s take an example: we all are familiar with laptops, right? We play games, create documents or write programs, etc. While doing this most people like to listen to music. In short, perform multiple tasks at the same time. In another example, when shops have too many customers then the shopkeeper will do billing and count the number of items packed into bags, and also answer to the other customers for the same. This is an example of concurrency in simple words.

So in technical terms, Concurrency means performing/processing more than one task parallelly at the same time. Also, we can say that allowing multiple pieces of the code to run at the same time.Swift 5.5 onwards, Async/await functions write asynchronous code without using completion handlers to return values.

2. What is Async?

Async stands for asynchronous and can be seen as a method attribute making it clear that a method performs asynchronous work. It provides non-locking functionality to the program.

3. What is Await?

Await is a keyword to be used for calling an asynchronous method. You can see them as a pair of shoes, without one, the other is useless, in swift as one will never go without the other

“Await is awaiting a callback from his buddy async.”

Syntax:

  • By adding the async keyword to any function:

  • Async can also return a result:

  • Calling async function:

Let’s take an example:

Although, if we want to execute other tasks or functions while the async function is being executed, then we need to put the“async” keyword in front of the variable declaration. In this case, the “await”keyword should be placed before the variable where we are accessing the result of the asynchronous function.

The syntax for error handling:

  • By adding async throws to any function:

  • Async throws can also return a result:

  • At the time of calling function:

4. Control Flow Cycle

  • Synchronize Function:

sync-flow-swift

Source

 

  • Async/Await Function:

async-flow-swift

Source

Example:

  • Before async/await

before-async-swift

Source

  • After using async-await

Source

Conclusion

The above example of Async/await in swift allows for concurrency, which will improve the readability of complex async code. It eliminates the need for completion closures and calls into multiple async methods. In addition, we get more flexibility into code.
For more information: Check this reference video

Written By,

iOS Developer at Yudiz Solutions Pvt. Ltd