async/await is a language feature added to Swift 5.5. It’s part of Apple’s new approach to structured concurrency & asynchronous programming. it is a nod to same language feature that’s existed in JavaScript for quite some time now. It provides a much cleaner code experience over traditional callbacks and/or Combine.

The old way to make an asyncronous call

The following example uses URLSession data task to make an asynchronous call to a cloud endpoint using traditional callbacks implemented as closures:

let url = URL(string: "https://www.example.com/")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    if let error = error {
        // handle error
        return
    }
    // happy path
}
task.resume()

The new way to make an asyncronous call

try {
    let url = URL(string: "https://www.example.com/")!
    let (data, response) = try await URLSession.shared.data(for: url)
    // happy path
} catch {
    // handle error
}

I’ve surrouned the code with a try catch but we could just as easily defer the handling of the error in the caller and do away with the try catch here.

Quite a difference, isnt it? This brevity of code is one of the advantages of async / await over more traditional ways of doing asynchronous programming.

Conclusion

async / await is now the preferred way of writing concurrent code in Swift.

References

Meet Swift Concurrency