bunana bunana - 6 months ago 64
Swift Question

PromiseKit branching promise

Suppose you have a branch in your promise chain that could either return nothing or an AnyObject promise. What would you specify as the return type of the 'then' closure? For example:

func sample() -> Promise<AnyObject> {
return Promise { fulfill, reject in
fulfill(1)
}
.then { _ -> Void in
if false {
return Promise { fulfill, reject in
fulfill(0)
}
}
}
}


If I put Void as the return type for the 'then' closure I get a seg fault; if I put Promise as return type then I get an error:

missing return in a closure expected to return Promise<AnyObject>


Any suggestions?

Thanks

Answer

Based on the code sample, I see no reason to return an AnyObject. If you want to optionally return Void or an Object, then make a promise that contains an optional.

func sample() -> Promise<AnyObject?> {
    return Promise { fulfill, reject in
        functionForGettingObjectWithCallback() { result: AnyObject? in
            fulfill(result)
        }
    }
}