我有一个在 Objective-C 中定义的协议(protocol),例如:
@protocol MyProtocol <NSObject>
- (void)doStuffWithDictionary:(NSDictionary*)dict
andString:(NSString*)str1
andOptionalString:(NSString*)str2
andOptionalArray:(NSArray*)arr
callback:(void (^)(id result))onSuccess;
@end
...我正在尝试在 Swift 中定义一个实现此协议(protocol)的类,例如:
class MyImpl : Operation, MyProtocol {
func doStuff(withDictionary dict: [AnyHashable : Any]!,
andString str1: String!,
andOptionalString str2: String? = nil,
andOptionalArray arr: NSArray? = nil,
callback onSuccess: ((Any?) -> Void)! {
...
}
}
但是,我遇到了如下构建错误:
Type 'MyImpl' does not conform to protocol 'MyProtocol'
note: candidate has non-matching type '([AnyHashable : Any]!, String!, String?, NSArray?, ((Any?) -> Void)!'
func doStuff(withDictionary dict: [AnyHashable : Any]!, andString str1: String!, andOptionalString str2: String? = nil, andOptionalArray arr: NSArray? = nil, callback onSuccess: ((Any?) -> Void)!
它似乎对 andOptionalArray arr: NSArray 感到不安? = 无
参数。此处使用的正确语法是什么?
最佳答案
我把你的协议(protocol)放在一个项目中并在<ProjectName>-Bridging-Header.h
中导入它, 并且自动完成建议使用以下语法:
public func doStuff(with dict: [AnyHashable : Any],
andString str1: String,
andOptionalString str2: String,
andOptionalArray arr: [Any],
callback onSuccess: @escaping (Any) -> Void) {
}
如果你想要 String
和 [Any]
要作为可选项导入,您需要将它们标记为 nullable
在 Objective-C 中:
@protocol MyProtocol <NSObject>
- (void)doStuffWithDictionary:(NSDictionary*)dict
andString:(NSString*)str1
andOptionalString:(nullable NSString*)str2
andOptionalArray:(nullable NSArray*)arr
callback:(void (^)(id result))onSuccess;
@end
正如@MartinR 在评论中建议的那样:
Go to the header file where the protocol is defined, and choose "Generated Interface" from the "Related Items" popup in the top-left corner. That will show you the exact Swift method signature that you have to implement.
这也适用,并为不同版本的 Swift 提供不同的接口(interface)。
关于objective-c - 在 Swift 中实现 Objective-C 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52005075/