我们正在将现有类从 Objective-C 迁移到 Swift。在 View Controller 类中,我正在实现一个协议(protocol)并尝试将 View Controller 添加为其中包含的对象的委托(delegate)。当我尝试在 Swift 中添加“self”作为对象的委托(delegate)时,出现以下编译错误:
Cannot call value of non-function type '((ListenerProtocol) -> Void)?
这是 Obj-C 中的现有实现
@interface SomeViewController : UIViewController <ListenerProtocol> ...
并将类添加为监听器(委托(delegate))
[manager addListener:self];
这没有任何问题。但是 Swift 版本在看似相同的代码中失败了。这是同一调用的 Swift 版本:
@objc class SomeSwiftViewController: UIViewController, ListenerProtocol ...
以及对“addListener”的调用
manager?.addListener(self)
我已通过检查在运行时成功验证“self”是一个 ListenerProtocol 对象:
if self.conformsToProtocol(ListenerProtocol){
// ...
}
在包含委托(delegate)属性的对象中,addListener 方法在 Objective-C 中定义如下:
- (void)addListener:(id<ListenerProtocol>)listener {
// ...
}
Swift 类完全实现了 ListenerProtocol 中定义的所有方法。我不明白为什么这在 Swift 中不起作用。谁能提出建议?谢谢!
最佳答案
问题不在于 ListenerProtocol
,而在于 manager
实现的协议(protocol)。从类型来看,addListener
似乎是作为可选方法提供的。注意函数类型末尾的问号:
((ListenerProtocol) -> Void)?
这通常发生在(实际上,我认为它只发生在)Objective-C 可选协议(protocol)方法上。
您应该能够编写 manager?.addListener?(self)
或 manager?.addListener!(self)
。
关于Swift 无法识别 Objective-C 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38274771/