Asynchronous programming is a common requirement of any iOS application. The ability to perform task on a separate thread and not disturbing or blocking the user interface is always considered a good practice. In iOS 15 and Swift 5.5 Apple introduced async/await feature, which allows developers to easily implement asynchronous tasks with increased clarity and less lines of code.
In this article, we are going to take a look at how you can use async/await, continuation and actors in your iOS application.
Asynchronous Programming Using Callbacks
Before we jump into the new async/await features, we need to see how things are handled currently. It is by looking at the the past, we can appreciate the future.
For this example we are going to use JSONPlacefolder API to fetch all posts. The implementation of our client is shown below:
We all have implemented similar code in our application. The main issue with the above code is that you need to remember to return from the guard clauses. The other issue is the overall length of the code. For an operation like this, it turns out to be 10–15 lines of code.
In the next section, we are going to implement the same code but using the new async/await features.
It is definitely a welcome change in Swift language and it will allow developers to write better and clear concurrency code. Now, let’s check the async/await implementation for the
getAllPosts function as implemented below.