There was an official release iOS 15, which means developers have access to a new version of Xcode number 13, and with it a new version of the language Swift – 5.5.
In this version of the language, the developers from Apple have added a lot of long-awaited changes. The biggest of them are related to the concurrency mechanism.
Async/Await
We should remember that nowadays asynchronous code mostly uses delayed closure call. And sometimes, if a work involves many calls to asynchronous code, it can turn into a large, confusing, unreadable mass – Pyramid of doom.
Let’s look at a simple example. First we have to get a list of ids from the server, then do some hard work with those ids and load the result back to the server.
With the release of Swift 5.5 and the advent of async/await, it will become much easier for developers to write this type of code. Let’s rewrite our code for the new paradigm.
As you can notice the code is much cleaner and clearer, the calls are similar to calling synchronous code, except for await.
Now let’s understand a little bit how it all works.
When we get to the first await fetchIds() Swift will pause the current thread and wait for the asynchronous code to finish, during this time it can load our thread with some other work.
Once we get a result from fetchIds() , we move on to the next asynchronous call and step 1 is repeated.
After we get the result from performSomeWork(for:), we have the usual synchronous code foo(), which will be executed in the current thread and nothing will be paused.
Then on the await upload() call, we again pause our thread until we get the result. When we get the result, we will continue to execute our program.
As you can see, everything is simple and straightforward enough, with Swift doing the hardest work under the hood. But of course there are limitations; this asynchronous code can only be called in a few places:
- In other asynchronous functions.
- In the main() function labeled @main of other structures, classes, or enums.
- In the new Task structures available in iOS 15.
Therefore, we can conclude that async/await is kind of a language feature, but most likely you can use them in limited places, if your application target is not iOS 15.