Open Source Library Bringing Scala Inspired Futures To Swift

Late last year I mentioned a library providing a nice implementation of promises in Swift.

Here’s an open source Swift library submitted by Le Van Nghia that simplifies creating asynchronous code called Future.

Future is inspired by futures from the Scala programming language, and can greatly reduce the code required when handling many asynchronous operations.

This example from the readme shows some typical asynchronous code:

 func requestRepository(repoId: Int64, completion: (Repository?, NSError?) -> Void) {}
 func requestUser(userId: Int64, completion: (User?, NSError?) -> Void) {}

// get owner info of a given repository
 requestRepository(12345) { repo, error in
    if let repo = repo {
        requestUser(repo.ownerId) { user, error in
           if let user = user {
               // do something
           } else {
               // error handling
           }
        }
    } else {
        // error handling
    }
 }

Which could be simplified using Future to:

let future = requestRepository(12345)
        .map { $0.ownerId }
        .flatMap(requestUser)

future.onCompleted { result in
    switch result {
        case .Success(let user):   println(user)
        case .Failure(let error):  println(error)
    }
}

You can find Future on Github here.

A nice implementation of futures in Swift.

Original article: Open Source Library Bringing Scala Inspired Futures To Swift

©2015 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *