For those who aren’t familiar with the concept of asynchronous tasks and how iOS handles them, async/await will be a painless and intuitive way to learn how to work with them. For those who have been fighting against this issue using completionHandlers, async/await is here to make your life much easier – and your asynchronous functions code much shorter.
But async/await isn’t an iOS invention – not even the keywords they chose for this. This pattern has been around for a long time now and javascript – and its frameworks – have been using these keywords for a while as well. With Apple adopting this nomenclature, it is easier to map this solution throughout different programming languages.
While the synchronous function will execute one command after the other and will not release the thread where it’s running until it has finished, an asynchronous function will release the thread while waiting on something to complete. For this, Swift uses closures, better known as completionHandlers. However, this approach has a few disadvantages:
- CompletionHandlers are not the most intuitive thing to understand if you are not familiar with closures.
- If you have at least one nested completionHandler (also known as pyramid of doom), all the indentation could make your code harder to read.
- If you have some logic to do when you receive your response from the asynchronous call – even just checking for errors – you need to make sure to don’t forget to call the completionHandler before exiting your function (you wouldn’t want to leave it uninvoked!) and also to not call it more than once (this could cause unexpected behaviors).
Thankfully, in Swift 5.5 Apple introduced async/await ?. To declare an asynchronous function, all you have to do it is to add the keyword async after the closing parenthesis of that function as follows: