Why You Should Use Async/Await Over Closures Moving Forward
Since Apple released Async/await in 2021, it has made writing asynchronous code amazingly pleasant for iOS developers. In addition to the out-of-the-box performance and safety benefits, writing asynchronous code with async/await feels like you’re writing synchronous code, which we write most of the time. Writing straightline code rather than nested closures allows us to better express our intent to others. Using the combination of async/await and throws also makes handling errors straightforward.
Async/await was designed to resemble code we write everyday. It removed many of the frictions that came with writing and maintaining closures. For example, rather than capturing the return values on the right (like with closures), the return value of an async/await function is assigned to a variable on the left. This makes it just like your most basic function. You also no longer need to concern yourself with capturing the outer scope to access those values from within the closure. Which, if you had simply forgotten to add the weak keyword in front of your variables or self, you would have had a memory leak in your app, which is never a good thing.
Being able to write code that’s idiomatic and easy to parse is beneficial in many facets. For instance, you’ll write less lines of code which means it’ll be easier to maintain. You’ll also find the intent of your logic easier to maintain in your head. And it’ll ultimately feel like the style of code you write the most often.
One of the features I find most useful is how easy it makes handling errors. Errors seamlessly propagate downstream and could be parsed by individual catch blocks that will execute additional code, such as triggering events and handling any unhappy path. Unlike with closures where you can accidentally leave out an vital completion call, using try await, Swift warns you if you leave out a throw, which makes our code safer.
Summary
This article introduces the core advancements that Swift has made in writing asynchronous code using Async/await. Async/await is here to stay, and iOS Developers should begin using it and advocating for its adoption in their organization if they aren’t already.
That’s all, my friends. I hope this post unblocks you from any ongoing challenge you may be facing. If you have any questions or edge cases you’d like to discuss, just leave a comment below. If you want to support this blog you can Buy Me a Coffee. You can also connect with me on LinkedIn and Twitter, where I share all my new posts.