Converting closure-based code into async/await in Swift

Converting closure-based code into async/await in Swift

This article is part of my Modern Concurrency in Swift article series.

This article was originally written creating examples using Xcode 13 beta 1. The article, code samples, and provided sample project have been updated for Xcode 13 beta 3.

To better benefit from this article, you should be familiar with async/await. If you aren’t, feel free to read the first part of this article series: Understanding async/await in Swift.

[…]

Swift provides a few methods we can use to convert callback-based code into async/await: withCheckedContinuation and withCheckedThrowingContinuation. The difference between the two is the latter is used for code that throws errors. I call these methods explicit continuations.

[…]

Continuations must be called exactly once, therefore there must be a continuation call within every branch of withCheckedThrowingContinuation. If you forget to call a .resume, things could go awry. Luckily, Swift will let you know.

[…]