我目前正在尝试将项目从Swift 2迁移到Swift 3,我看到一些objc属性块的问题。
我有这个objc类:
@class Result;
typedef id (^mapResultFunction)(id value);
typedef Result * (^flatMapResultFunction)(id value);
typedef void(^resultSuccess)(id value);
typedef void(^resultFailure)(NSError *error);
@class AsyncResult;
typedef AsyncResult * (^flatMapAsyncResultFunction)(id value);
typedef Result * (^catchFailureResultFunction)(NSError *error);
@interface AsyncResult : NSObject
@property (nonatomic, strong, readonly) AsyncResult * (^success)(resultSuccess success);
@property (nonatomic, strong, readonly) AsyncResult * (^failure)(resultFailure failure);
在Swift 2中,这种用法编译得很好:
asyncResult
.success { result in
// show result
}?
.failure { error in
// show error
}
但是现在使用Swift 3,我得到了这个编译错误:
Cannot call value of non-function type '((resultSuccess?) -> AsyncResult?)!'
我看到生成的Swift代码是:
public typealias mapResultFunction = (Any?) -> Any?
public typealias flatMapResultFunction = (Any?) -> Result?
public typealias resultSuccess = (Any?) -> Swift.Void
public typealias resultFailure = (Error?) -> Swift.Void
public typealias flatMapAsyncResultFunction = (Any?) -> AsyncResult?
public typealias catchFailureResultFunction = (Error?) -> Result?
open class AsyncResult : NSObject {
open var success: ((__ObjC.resultSuccess?) -> AsyncResult?)! { get }
open var failure: ((__ObjC.resultFailure?) -> AsyncResult?)! { get }
}
这些__ObjC
看起来很可疑,所以我尝试编写自己的代码:
class AsyncResult {
var success: (((Any) -> (Void)) -> AsyncResult?)!
var failure: (((Error) -> Void) -> AsyncResult?)!
}
这样称呼它最终会起作用:
let r = AsyncResult()
r.success { result in
print("Hi")
}?.failure { failure in
print("Error")
}
有没有人知道Swift 3中有什么变化? 我能做些什么来解决这个问题?
答案 0 :(得分:0)
我找到了罪魁祸首。 问题实际上是在关闭内部。
asyncResult
.success { result in
showResult(result)
}?
.failure { error in
// show error
}
当showResult
期待AnyObject
时。在Swift 3中,它现在是Any
...
你会认为Xcode会显示该行中的错误......