NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

What’s the difference between await and async let?

Paul Hudson    @twostraws   

Updated for Xcode 13.3

Swift lets us perform async operations using both await and async let, but although they both run some async code they don’t quite run the same: await immediately waits for the work to complete so we can read its result, whereas async let does not.

Which you choose depends on the kind of work you’re trying to do. For example, if you want to make two network requests where one relates to the other, you might have code like this:

let first = await requestFirstData()
let second = await requestSecondData(using: first)

There the call to requestSecondData() cannot start until the call to requestFirstData() has completed and returned its value – it just doesn’t make sense for those two to run simultaneously.

On the other hand, if you’re making several completely different requests – perhaps you want to download the latest news, the weather forecast, and check whether an app update was available – then those things do not rely on each other to complete and would be great candidates for async let:

func getAppData() -> ([News], [Weather], Bool) {
    async let news = getNews()
    async let weather = getWeather()
    async let hasUpdate = getAppUpdateAvailable()
    return await (news, weather, hasUpdate)

So, use await when it’s important you have a value before continuing, and async let when your work can continue without the value for the time being – you can always use await later on when it’s actually needed.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.