Swift 无法识别 Objective-C 协议(protocol)

标签 objective-c swift

我们正在将现有类从 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/

相关文章:

objective-c - RestKit 0.9.3 连接关系 :withObjectForPrimaryKeyAttribute:

c++ - 在 C++ 文件中包含 Objective-C 头文件

swift - 快速杀死进程

ios - 如何在 iOS 应用程序和今日 View 扩展之间共享数据

objective-c - 同一 View 中的两个 UITableView

objective-c - 编译时ARC错误

objective-c - NSTimer with block——我做的对吗?

ios - 设置 MPNowPlayingInfoCenter 与其他背景音频播放

javascript - 查找图像宽度、高度以及起点和终点

ios - SwiftUI - 如何将一个 TextView 与另一个 TextView 垂直对齐以制作类似于具有适当对齐方式的表格的内容?