Open Source Swift Library Providing A Nice Implementation of Promises

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.

FacebookTwitterDiggStumbleUponGoogle Plus

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.

Leave a Reply

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