The Always Right Institute

submited by
Style Pass
2021-06-18 13:00:06

The secret Apple doesn’t want you to know about: It has been shipping an async/await runtime for years. Let’s have a look on how to use it from within Swift!

In another episode of “forums are awful”, people go at length to complain about Swift Concurrency not being available on iOS 14 / macOS 11 and before. Yes, that is right, the new async/await requires iOS 15 or later.

Fret not. If you really, really want to use async/await and can’t wait, there is a secret Apple isn’t advertising: It is already shipping an async/await runtime since about iOS 12 (probably longer). You have to give up a little typesafety, but that’s overrated anyhow. Let’s have a look on how to use it.

We ask URLSession to download some data asynchronously, and await the results (the data fetched and the response). Note that (as usual) await can only be run from within an async function, so we setup a mainActor() first.

If you want to follow along, the easiest way is to create a macOS Tool project in Xcode (no Xcode 13 required, this also works with Xcode 12 and probably even xCode X). Just dump the code into the main.swift.

Leave a Comment