我似乎不知道如何从 Swift 调用 Objective-C block !
我有以下 Objective-C 方法:
- (void)myMethod:(NSDictionary *)selection success:(MyBlock)success;
MyBlock 所在位置:
typedef void(^MyBlock)(BOOL success, NSDictionary* options);
它要么提示它无法转换:
"Cannot convert value of type '(Bool, Dictionary<AnyHashable, Any>) -> ()' to expected argument type 'MyBlock!' (aka 'ImplicitlyUnwrappedOptional<(Bool, Optional<Dictionary<AnyHashable, Any>>) -> ()>')"
或者当我尝试使用以下任一方法从 Swift 调用该方法时,我收到 SIGABRT:
myInstance.myMethod(myOptions) { (success, options) in
...
}
myInstance.myMethod(myOptions) { (success: Bool, options: Dictionary<AnyHashable, Any>?) in
...
}
myInstance.myMethod(myOptions) { (success: Bool!, options: [AnyHashable: Any]?) in
...
}
myInstance.myMethod(myOptions, success: { (success, options) in
...
})
myInstance.myMethod(myOptions, success: { (success, options) in
...
} as MyBlock)
myInstance.myMethod(myOptions, success: { (success: Bool, options: Dictionary<AnyHashable, Any>?) in
...
})
myInstance.myMethod(myOptions, success: { (success: Bool!, options: Dictionary<AnyHashable, Any>?) in
...
})
myInstance.myMethod(myOptions, success: { (success: Bool!, options: Dictionary<AnyHashable, Any>?) in
...
} as MyBlock)
myInstance.myMethod(myOptions, success: { (success: Bool!, options: [AnyHashable: Any]?) in
...
})
myInstance.myMethod(myOptions, success: { (success: Bool, options: [AnyHashable: Any]?) in
...
})
我该怎么办?
最佳答案
您的 MyBlock 的等效 swift 代码:
typedef void(^MyBlock)(BOOL success, NSDictionary* options)
- (void)myMethod:(NSDictionary *)selection success:(MyBlock)success;
如下:
public typealias MyBlock = (Bool, [String : Any]) -> (Void)
func myMethod(selection: [String : Any], success: MyBlock)
例如,当您使用 myMethod 时:
self.myMethod(selection: yourDictionary) { (success, options) -> (Void) in
//handle here
}
关于Swift 相当于我的 Objective-C block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48159557/