swift - 如何创建可以在数组中使用的 Swift 协议(protocol)?

标签 swift protocols

我有 2 个不同的类(NSObject、RealmObject),它们应该符合一个通用协议(protocol) Listening。

protocol Listening: class {
  var filter: String? { get }
}

然后我有一个包含数组 var allListeningObjects: [Listening] 的父类,它应该包含所有符合此协议(protocol)的对象。但在我运行它之前,我得到了这个错误:Type 'Listening' does not conform to protocol 'Hashable'

我愿意接受任何可以使这项工作成功的建议。

最佳答案

考虑到您遇到的错误 - 看起来您正在尝试将 Listening 协议(protocol)用作字典中的键类型或集合中的元素类型 - 并且不是数组中元素的类型。仔细检查 allListeningObjects 的类型定义并确保它实际上是一个数组,而不是集合或字典。

如果您打算在此上下文中使用您的Listening 协议(protocol) - Apple has some nice documentation on how to implement 可哈希

关于swift - 如何创建可以在数组中使用的 Swift 协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43334571/

相关文章:

ios - 找不到目标 'MyCustomFramework' 的模块 'x86_64-apple-ios-simulator' ;找到 : arm64, armv7-apple-ios,arm64-apple-ios,arm,armv7

ios - 创建一个 swift ios 框架

c - 两个软件实体(Uart/I2C/等)之间串行通信的简单实现

Swift 声明 AnyClass 对象实现协议(protocol)

ios - 在 Swift 的 collectionViewCell 中缓存图像?

ios - 从类实现时 UIButton 不可单击

ios - Swift 中的 NSExpression 计算器

ios - 子类的 UIView 标准协议(protocol)

udp - RTP 数据包最大大小?

java - 如何破译 ASN/BER 数据包