首页 > 解决方案 > 带有协议的观察者模式

问题描述

我有一个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'

有没有办法做观察者模式?

标签: swiftobserver-pattern

解决方案


推荐阅读