Understanding Swift’s Async/Await Model with Exception Handling

Wayne Bishop
Swift Algorithms & Data Structures
3 min readJul 27, 2021

--

In my previous articles on structured concurrency with Swift, I walked through some practical examples of how I envision developers using the async/await syntax to streamline and simplify asynchronous code. This article extends the basics of async / await with an existing standard — exception handling.

While I fully support the idea that syntax comes secondary to solution design, there are times when understanding syntax goes a long way to mastering the process. In Swift, language features like optionals and closures come to mind in addition to exception handling. Let’s review two scenarios of exception handling when combined with structured concurrency.

Building The Exception Model

To start, let’s build a model that mimics the process of downloading a series of images. While connecting to an external process to retrieve images is reasonably common, it certainly doesn’t mean its success is guaranteed. As such, we can extend our implementation to support a custom ImageError enum that to illustrate standard exceptions:

enum ImagesError: Error {
case timeout
case invalidFormat
case invalidSize
case invalidUrl
}

With our Error enum type in place, let’s build out the process to download images. As part of…

--

--