Search code examples
iosswiftpromisekit

Migrating from PromiseKit wrap


I'm trying to get rid of some warnings in my code and can't seem to migrate away from PromiseKit's wrap. Specifically, in 6.0 the release details say I shouldn't use it and should use init(resolver:) instead.

I had a function:

func foo(arg1: Int, arg2: Int, completionHandler: @escaping () -> ())

The following was working:

wrap({ foo(arg1: val1, arg2: val2, completionHandler: $0) })

I tried to change it to (what the release notes suggest):

Promise { foo(arg1: val1, arg2: val2, completionHandler: $0.resolve) }

This produced an error Generic parameter 'T' could not be inferred so I tried to fix that:

Promise<Void> { foo(arg1: val1, arg2: val2, completionHandler: $0.resolve) }

But that triggered a different error Unable to infer closure type in the current context and I'm not sure where to go from there.


Solution

  • Below is the deprecated method used to wrap the methods.

    @available(*, deprecated, message: "See `init(resolver:)`")
    public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise<Void> {
        return Promise { seal in
            try body(seal.resolve)
        }
    }
    

    As we can see, the completion closure is taking an Optional Error argument so i am suspicious how your older code was working by passing a wrong closure. I feel your foo method declaration should be like this,

    func foo(arg1: Int, arg2: Int, completionHandler: @escaping (Error?) -> Void) {
        // body
    }
    

    However for the latest PromiseKit, you can update the completionHandler by passing an Optional Error as above to create Promises as below,

    Promise { foo(arg1: 1, arg2: 2, completionHandler: $0.resolve) }