Member-only story
Sequential vs Concurrent Operations with Async / Await in Swift
Original article published here.
In my previous article on structured concurrency with Swift, I highlighted many new asynchronous programming concepts anticipated with Swift 5.5. New keywords like Actors, MainActor, Async, and Await, will quickly be used in regular Swift applications, helping streamline complex operations and increase efficiency.
What’s nice about the new model is that it provides a great platform to express one’s ideas clearly, depending on the data scenario. To illustrate, let’s review how one can use async/await commands to replicate sequential versus concurrent operations. To start, let’s write sample code for retrieving photos from an external service:
class Photos {
func getPhoto(inGallery name: String) async -> String {
for _ in 1...10 {
print("sleeping for \(name)")
await Task.sleep(20)
}
return name + "_IMG001"
}
}
As we can see, the type contains a single async method named getPhoto. Also, notice the type isn’t an Actor but is a (regular) class. To simulate the idea of a long-running process, we’ve also added a sleep command in the method-body.