swift - 带有协议的观察者模式
问题描述
我有一个P
具有notify
功能的协议,我有点在观察者模式中使用它。
这就是我的意思:
protocol P: AnyObject, Hashable {
func notify()
}
extension P {
// Compare by reference
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
static func == (lhs: Self, rhs: Self) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
我可以有多个听众:
class Implemenation1: P {
func notify() {
print("Impl 1")
}
}
class Implemenation2: P {
func notify() {
print("Impl 2")
}
}
我正在尝试像这样使用它:
var set: Set<P> = [Implemenation1(), Implemenation2()]
for x in set {
x.notify()
}
但是,我收到一条错误消息
error: protocol 'P' as a type cannot conform to 'Hashable'
有没有办法做观察者模式?
解决方案
推荐阅读
- javascript - html 中的 Srcset 混淆
- swift - 如何在 SwiftUI 中创建蓝视图?
- android - 尝试使用 android.support 为 android 添加 MSAL
- vue.js - 无法在其他组件中使用文件上传组件
- windows - 批处理脚本错误:获取一年中的哪一天
- node.js - multer 上的 fileFilter 仍然允许所有文件类型
- c# - 如何使用流,生成 csv 文件,在 .NET Core 3.1 中使用 CsvHelper?
- c# - 如何在 C# 中使用 IGeometry (NetTopolgy) 创建圆并存储为 IGeometry 类型
- excel - excel - 从交替列中查找行中的最后一个非空白单元格
- flutter - 以组的形式显示发送者和接收者之间的消息列表,每个组标签对应于日期