Use Async And Await In Swift

Daily Coding Tip 020

Here’s a way to use experimental concurrency, which is not yet part of Apple’s implementation of Swift.

I wanted this tutorial to use SwiftUI, but it turns out that won’t be possible.

I learnt how to use async and await from a Oh My Swift tutorial, and I was hoping to do something similar in SwiftUI. After trying I reached out to Rizwan Ahmed who wrote the original tutorial, and he asked about on the Swift forums.

The answer there came from Jonathan Prescott:

Looks like the toolchain Foundation doesn't include a method/function that SwiftUI relies on. Apple only guarantees that SwiftUI (which is an Apple-private framework) only works with Apple-sanctioned versions of its other frameworks, like Foundation, which on Darwin may be semi-private (parts open-source, parts proprietary to Apple). Swift development snapshots should be considered beta or alpha software. Most useful for command line tools, may be iffy when trying to mix with the release Apple ecosystem. You can probably get away with using the snapshot compiler, standard library, and the other tools, but frameworks like Foundation are going to be touch and go.

You can access snapshots of the development toolchain on the official Swift website by downloading the Xcode version. This is an installer that will add the toolchain to Xcode automatically, and you can choose between them using Xcode > Toolchains from the top menu bar. Alternatively, you can use Xcode > Preferences > Components to choose between toolchains. The final step is more complicated. Go to Build Settings, search for Swift flags, and double click the empty text field.

Add the following value:

-Xfrontend -enable-experimental-concurrency

This is where any SwiftUI project will fail. Even a completely empty SwiftUI project will fail when you try to run it, and you’ll receive a console log similar to mine.

Instead I’m using UIKit with a storyboard that has a UIImageView on it. Use Cmd + Shift + L to open the library, search for an Image View and drag one onto your app. Open the storyboard, choose Editor > Assistant from the top menu, right-click the Image View and draw a line into the code that should have opened to the right. This will create an outlet, which I’ve called imageView.

Everything else is covered by this code. We have a URL for the image that is shown at the top of this tip.

We have an await function that sets the image after it is downloaded, and an async function that asynchronously downloads it.

Notice that I am setting the image on the main thread in awaitImage. The await keyword cannot be used inside this block, which is why I am not enclosing both statements in the block.

Interestingly this code will also fail if getImage is not static for some reason.

Get more Daily Coding Tips in your inbox!