Async let in Swift


Greetings, traveler!

The previous article looked at various ways to use Tasks in Swift Concurrency. Here, I would like to take a closer look at the possibilities of asynchronously executing operations within a single Task using async let.

In the previous article, we had such a code example.

func getImage(id: Int) async -> UIImage? {
    print("Image id: \(id)")
    
    return images[id]
}

func getImages() {
    Task {
        let firstImage = await getImage(id: 0)
        let secondImage = await getImage(id: 1)
        
        let images = [firstImage, secondImage]
    }
}

We found out that the console will show the following text.

We can see that all operations were performed sequentially. Sure thing, running them in parallel would positively affect the application’s performance. We can do it with async let.

func getImages() {
    Task {
        async let firstImage = await getImage(id: 0)
        async let secondImage = await getImage(id: 1)
        
        let images = await [firstImage, secondImage]
    }
}

Let’s look at the console again. The output seems different now and could be different each time, depending on how quickly the parallel operations are completed.

Conclusion

This tool can improve your code’s performance. However, like any tool, it is not suitable for all cases.

Alright, then. In the following article, we will continue to analyze the Tasks and discuss how and when to cancel them.