Promises are a great way for working with asynchronous operations and earlier this year I mentioned the Objective-C promises library PromiseKit who have added an experimental Swift variant to their library.
Here’s an open source Swift based library called Craft from Tommy Leung for promises that is based on the Promises/A+ standard with a very clean syntax.
This is a basic usage example showing Craft in action – note that operations are not automatically placed in a background thread like some of the Objective-C promises libraries:
let promise = Craft.promise({
(resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in
//some async action
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
//do something
usleep(250 * 1000)
dispatch_sync(dispatch_get_main_queue(), {
//resolve if all went well
resolve(value: value)
//or reject if there was a problem
reject(value: value)
})
})
})
promise.then({
(value: Value) -> Value in
//resolved successfully!
return nil
}, reject: {
(value: Value) -> Value in
//failed for some reason
return nil
})
And an example of how to use the array capabilities for times you want multiple promises to resolve before doing something:
let a = [
somePromise,
someOtherPromise,
anotherPromise
]
Craft.all(a).then({
(value: Value) -> Value in
if let v: [Value] = value as? [Value]
{
//v is an array of the Promise results
println(v)
}
return nil
})
You can find Craft on Github here.
A nice Swift based implementation of promises.
- A Library Adding Promises To Objective-C With Categories For Asynchronous Operations In The iOS SDK
- Examples: A Collection Of Popular Design Patterns Implemented In Swift
- An Open Source Library Implementing Over 40 Math Symbols As Custom Operators In Swift
- Extensive Swift Utility Library Inspired By Python’s Standard Library
- Tutorial: Using Generics To Implement KVO In Swift
Original article: Open Source Swift Library Providing A Nice Implementation of Promises
©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.