我们正在将现有的类从Objective-C迁移到Swift。在视图控制器类中,我正在实现协议,并尝试将视图控制器添加为其中包含的对象的委托。当我尝试在Swift中将“ self”添加为对象的委托时,出现以下编译错误:
Cannot call value of non-function type '((ListenerProtocol) -> Void)?
这是Obj-C中的现有实现
@interface SomeViewController : UIViewController <ListenerProtocol> ...
并将类添加为侦听器(委托)
[manager addListener:self];
这可以正常工作。但是Swift版本在看似相同的代码中失败了。这是同一调用的Swift版本:
@objc class SomeSwiftViewController: UIViewController, ListenerProtocol ...
以及对“ addListener”的调用
manager?.addListener(self)
我已经通过检查成功验证了'self'在运行时是ListenerProtocol对象:
if self.conformsToProtocol(ListenerProtocol){
// ...
}
在包含委托属性的对象中,在Objective-C中定义了addListener方法,如下所示:
- (void)addListener:(id<ListenerProtocol>)listener {
// ...
}
Swift类完全实现了ListenerProtocol中定义的所有方法。我不明白为什么这在Swift中不起作用。有人可以提出建议吗?谢谢!
问题不在于ListenerProtocol
,而是manager
实现的协议。按类型判断,addListener
似乎是作为一种可选方法提供的。注意函数类型末尾的问号:
((ListenerProtocol) -> Void)?
这通常发生在(实际上,我认为它只发生在)Objective-C可选协议方法上。
您应该能够编写manager?.addListener?(self)
或manager?.addListener!(self)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句