Exploring Promises in Swift

Michael Amundsen
2 min readSep 2, 2016

--

As I increasingly interact with the internet, the question of elegantly handling network calls keeps coming up. At Flatiron School, we were taught how to handle asynchrony with the standard tools available in Swift, namely closures. While closures by themselves absolutely have their place, when it comes to parsing objects and handling errors, they can get complicated and unwieldy pretty quickly. This led me to start looking for options to write cleaner code.

Enter the concept of promises and PromiseKit

(PromiseKit is a open source framework that implements the functionality of promises in Swift.)

So if I was making an API request to Foursquare with closures , the code may look something like this:

I would pass the data and error up the chain to additional functions that rely on the parameters passed into this completion block.

With promises, I can add substantial clarity to this code by handling data and errors in a much more concise and less ambiguous way.

The following code is a possible way to wrap an Alamofire request in a promise:

Now that we have the promise setup, we can call the .then(_:) function which passes a body containing the promise’s data:

This code executes once the Alamofire request is complete and the promise has been fulfilled. N.B. We do not fulfill the promise in the event of an API error. I can use this closure to process the data and populate venue location objects. Using firstly blocks, it would even be possible to chain the result of multiple then-completions.

While this is a simplistic implementation of a promise, it quickly becomes clear that promises provide cleaner error handling and simplified asynchrony in data models. This barely scratches the surface of promises but gives me a good starting place to explore them further in my projects to come.

--

--