Member-only story

Swift 5: How to do Async/Await with Result and GCD

Why wait for Apple to add Async/Await to Swift when you can have it now?

Michael Long
7 min readApr 30, 2019

Swift 5.0 brought several new language enhancements along with ABI stability, and one of those was adding Result to the standard library. Result gives us a simpler, clearer way of handling errors in complex code such as asynchronous APIs.

And especially when chaining multiple API calls together.

Overview

Using Result and Grand Central Dispatch (GCD), we’ll be able to write pure Swift code like the following:

    func load() {
DispatchQueue.global(qos: .utility).async {
let result = self.makeAPICall()
.flatMap { self.anotherAPICall($0) }
.flatMap { self.andAnotherAPICall($0) }

DispatchQueue.main.async {
switch result {
case let .success(data):
print(data)
case let .failure(error):
print(error)
}
}
}
}

Here our load function makes several consecutive API calls in the background, each time passing the result of one call to the next. We then handle the final result back on the main…

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (9)