简体   繁体   中英

Bridging from Objective C to Swift with PromiseKit

Using PromiseKit 2.0 with Swift 1.2, I'm trying to use a PMKPromise that was created in Objective C from Swift.

Objective C code:

@interface FooTest : NSObject
+ (PMKPromise *)promise;
@end

Swift code (I've tried a number of variations, none of which work. This one is closest to the example given at http://promisekit.org/PromiseKit-2.0-Released/ ):

FooTest.promise().then { (obj: AnyObject?) in
    self.obj = obj
}

Compiler error: Cannot invoke 'then' with an argument list of type '((AnyObject?) -> _)'

This doesn't work either:

FooTest.promise().then { (obj: AnyObject?) -> AnyPromise in
    return AnyPromise()
}

Similar error: "Cannot invoke 'then' with an argument list of type '((AnyObject?) -> AnyPromise)'"

There are two different promise classes in PromiseKit, one for Swift ( Promise<T> ) and one for ObjC ( AnyPromise ). The Swift ones are generic and Objective-C cannot see generic classes, so this is why there are two.

If Foo.promise() is meant to be used in both ObjC and Swift then you are doing the right thing. If however you only intend to use this promise in Swift then I suggest rewriting it as a Promise<T> .

To use an Objective-C AnyPromise ( PMKPromise is a deprecated alias for AnyPromise : prefer AnyPromise ) in Swift code you must splice it into a an existing chain.

someSwiftPromise().then { _ -> AnyPromise in
    return someAnyPromise()
}.then { (obj: AnyObject?) -> Void in
    //…
}

There should be a way to start from an AnyPromise, probably I will add this later today:

someAnyPromise().then { (obj: AnyObject?) -> Void in
    //…
}

Expect a 2.1 update. [edit: 2.1 pushed with the above then added]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM