objective-c - 在 Swift 中实现 Objective-C 协议(protocol)

标签 objective-c swift syntax protocols

我有一个在 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/

相关文章:

iOS 8 didReceiveAuthenticationChallenge 没有被 WKWebView Objective C 调用

iphone - 从 float 或 double 实例化 NSDecimalNumber 的正确方法

ios - 'NSDictionary ?' is not convertible to ' NSCopying'

ios - Swift - Firebase - 订单集合

c++ - 这个结构是什么意思 : bool operator == (const a& other) const;?

javascript - 如何阅读 Immutable/React 文档页面的代码示例

像 iOS 6 一样的 iOS 7 状态栏

ios - dispatch_after 会阻塞主线程吗?

ios - swift 4 "This class is not key value coding compliant"

java - else语句是语法错误?