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? = nil 感到不安范围。在这里使用的正确语法是什么?

最佳答案

我把你的协议(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/

相关文章:

iphone - NSString - 浮点数最多 1 位小数

objective-c - vImage无法将 channel 正确放回原处

ios - dismissViewControllerAnimated 关闭所有 View Controller 到 root [swift]

ios - 使用observedProgress时如何将UIProgressView重置为0

c - 为什么写在这里时没有正文?

objective-c - Mac : Check for keyboard events

objective-c - swift 3 : Stop it from converting [NSString] to [String]

Swift 1.2 : 'self' used before super. 初始化调用

c++ - 为什么要写->而不是。

javascript - 这是什么 JS 语法?表达式中的赋值? (x != null && (y = x))