0

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

rclark
  • 301
  • 3
  • 13
  • If you use `Promise` as the return type, you must return a Promise. Right now you're only doing that from inside `if false`, which will never be executed. – jtbandes May 13 '16 at 02:27
  • If I change to `func sample() -> Promise { return Promise { fulfill, reject in fulfill(1) }.then { _ -> Void in debugPrint("foo") }.then { _ -> Promise in if false { return Promise { fulfill, reject in fulfill(0) } } return Promise { fulfill, reject in fulfill(0) } } }` it works; but it seems kinda lame that I have to explicitly return an empty promise @jtbandes – rclark May 13 '16 at 02:44
  • What is your goal? Why do you have this `if false` branch? – jtbandes May 13 '16 at 02:44
  • Just to clarify that the closure could either return void or a promise resolved to some object; I'm not clear on the implementation of the PromiseKit's 'then' method and what it does under the hood @jtbandes – rclark May 13 '16 at 02:48
  • "could either return void or a promise" => that's not possible in Swift. A function must have a single return type. – jtbandes May 13 '16 at 02:52
  • @jtbandes Yea I mispoke. Suppose its possible for the closure to return two different types; for example: 1) Promise or 2) String. Im curious how you would indicate this in the closure return type – rclark May 13 '16 at 03:00
  • Like I said, there is no such thing. Perhaps you could use an enum instead. – jtbandes May 13 '16 at 03:00
  • @jtbandes Hmm, ok I see. Well I have to look into this some more. Thanks! – rclark May 13 '16 at 03:04
  • 1
    try returning an optional? – João Nunes May 16 '16 at 13:18

1 Answers1

1

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)
        }
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72