The easiest Promises in Swift

Here's another article of the serie "The easiest <something>". Previous one on Core Data here -> The easiest Core Data.

Swift 5 will most likely include async/await, which will be a revolution for handling concurrency at language level. See Chris Lattner's proposal here. In the meantime future/promises are a great abstraction that allow developers to better deal with concurrency and its derived problems.

So, here it is, let me introduce the easiest Future and Promises framework in Swift. No magic. No boilerplate. It's called Promis and it's available on GitHub.

Overview

Promis takes inspiration from the Objective-C version of JustPromises developed by the iOS Team of Just Eat which is really concise and minimalistic, while other libraries are more weighty.

I implemented this library with the main goal of replacing some legacy Objective-C code we had at Just Eat. For this reason, the new code had to be robust, nicely written and production ready. Surely I started from the existing implementation of JustPromises, kept the code minimalistic and added the following:

  • conversion to Swift 4
  • usage of generics to allow great type inference that wasn't possible in Objective-C
  • overall refactoring for fresh and modern code
  • remove the unnecessary and misleading concept of Progress causing bad patterns to emerge

You can read about the theory behind Future and Promises on Wikipedia, here are the main things you should know to get started.

  • Promises represent the promise that a task will be fulfilled in the future while the future holds the state of such resolution.
  • Futures, when created are in the unresolved state and can be resolved with one of 3 states: with a result, an error, or being cancelled.
  • Futures can be chained, allowing to avoid the pyramid of doom problem, clean up asynchronous code paths and simplify error handling.

Promis brags about being/having:

  • Fully unit-tested and documented 💯
  • Thread-safe 🚦
  • Clean interface 👼
  • Support for chaining ⛓
  • Support for cancellation 🙅‍♂️
  • Queue-based block execution if needed 🚆
  • Result type provided via generics 🚀
  • Keeping the magic to the minimum, leaving the code in a readable state without going off of a tangent with fancy and unnecessary design decisions ಠ_ಠ

Alternatives

Other open-source solutions exist such as:

Usage

The following example should outline the main benefits of using futures via chaining.

let request = URLRequest(url: URL(string: "http://example.com")!)

// starts by hitting an API to download data
getData(request: request).thenWithResult { data in
    // continue by parsing the retrieved data
    parse(data: data)
}.thenWithResult { parsedData in
    // continue by mapping the parsed data
    map(data: parsedData)
}.onError { error in
    // executed only in case an error occurred in the chain
    print("error: " + String(describing: error))
}.finally(queue: .main) { future in
    // always executed, no matter the state of the previous future or how the chain did perform
    switch future.state {
        case .result(let value):
            print(String(describing: value))
        case .error(let err):
            print(String(describing: err))
        case .cancelled:
            print("future is in a cancelled state")
        case .unresolved:
            print("this really cannot be if any chaining block is executed")
        }
}

The functions used in the example have the following signatures:

func getData(request: URLRequest) -> Future<Data>
func parse(data: Data) -> Future<[Dictionary<String,AnyObject>]>
func map(data: [Dictionary<String,AnyObject>]) -> Future<[FooBar]>

Promises and Futures are parametrized leveraging the power of the generics, meaning that Swift can infer the type of the result compile type. This was a considerable limitation in the Objective-C world and we can now prevent lots of issues at build time thanks to the static typing nature of the language. The state of the future is an enum defined as follows:

enum FutureState<ResultType> {
    case unresolved
    case result(ResultType)
    case error(Error)
    case cancelled
}

Promises are created and resolved like so:

let promise = Promise<ResultType>()
promise.setResult(value)
// or
promise.setError(error)
// or
promise.cancel()

Continuation methods used for chaining are the following:

func then<NextResultType>(queue: DispatchQueue? = nil, task: @escaping (Future) -> Future<NextResultType>) -> Future<NextResultType>
func thenWithResult<NextResultType>(queue: DispatchQueue? = nil, continuation: @escaping (ResultType) -> Future<NextResultType>) -> Future<NextResultType> {
func onError(queue: DispatchQueue? = nil, continuation: @escaping (Error) -> Void) -> Future {
func finally(queue: DispatchQueue? = nil, block: @escaping (Future<ResultType>) -> Void)

All the functions can accept an optional DispatchQueue used to perform the continuation blocks.

Best practices

Functions wrapping async tasks should follow the below pattern:

func wrappedAsyncTask() -> Future<ResultType> {

    let promise = Promise<Data>()
    someAsyncOperation() { data, error in
        // resolve the promise according to how the async operations did go
        switch (data, error) {
        case (let data?, _):
            promise.setResult(data)
        case (nil, let error?):
            promise.setError(error)
        // etc.
        }
    }
    return promise.future
}

You could chain an onError continuation before returning the future to allow in-line error handling, which I find to be a very handy pattern.

// ...
return promise.future.onError {error in
    // handle/log error
}

Pitfalls

When using then or thenWithResult, the following should be taken in consideration.

...}.thenWithResult { data -> Future<NextResultType> in
    /**
    If a block is not trivial, Swift cannot infer the type of the closure and gives the error
    'Unable to infer complex closure return type; add explicit type to disambiguate'
    so you'll have to add `-> Future<NextResultType> to the block signature
    
    You can make the closure complex just by adding any extra statement (like a print).
    
    All the more reason to structure your code as done in the first given example :)
    */
    print("complex closure")
    return parse(data: data)
}

Please check the GettingStarted playground in the demo app to see the complete implementation of the above examples.

Installations via Cocoapods and Carthage are available.

Happy chaining! 🎉