我想创建一个具有默认 kvo 功能的协议(protocol)。但是,我在协议(protocol)扩展继承 NSObject 时遇到问题。当我尝试覆盖 observeValue(forKeyPath
时我收到错误 Method does not override any method from its superclass
.这是我正在尝试做的一些示例代码
protocol VideoTest {
var player:AVPlayer { get set }
func trackVideoStart()
}
struct ObserverContexts {
static var playerRate = 0
}
extension VideoTest where Self: NSObject {
func addPlayerObservers() {
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.rate),
options: ([.old, .new]),
context: &ObserverContexts.playerRate)
}
//gives error
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
}
}
由于我不能直接从 NSObject 继承,是否可以通过协议(protocol)扩展使用 KVO?
最佳答案
这是因为编译器会查找您在 VideoTest 协议(protocol)本身上覆盖的函数。 where 子句只是告诉它只在 VideoTest 是 NSObject 类型时才做扩展。
无论这是否有效,您实际上都不能这样做,因为扩展根本无法覆盖函数。请参阅扩展的 swift 文档 here特别是这一点:
NOTE
Extensions can add new functionality to a type, but they cannot override existing functionality.
关于使用 kvo 的快速协议(protocol)扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48194747/