Get Updates By E-mail 

Article Written By:
Johann Dowa

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.


  •  
  •  
  •  
  •  
  •  

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.

Comments