基于kvo的swift协议扩展

基于kvo的swift协议扩展,swift,protocols,avplayer,key-value-observing,Swift,Protocols,Avplayer,Key Value Observing,我想创建一个具有默认kvo功能的协议。但是,我在协议扩展继承NSObject时遇到问题。当我试图覆盖observeValue(forKeyPath时,我得到一个错误方法不会覆盖其超类中的任何方法 protocol VideoTest { var player:AVPlayer { get set } func trackVideoStart() } struct ObserverContexts { static var playerRate = 0 } extension

我想创建一个具有默认kvo功能的协议。但是,我在协议扩展继承NSObject时遇到问题。当我试图覆盖
observeValue(forKeyPath
时,我得到一个错误
方法不会覆盖其超类中的任何方法

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继承,是否可以通过协议扩展使用KVO?

这是因为编译器会在VideoTest协议本身上查找您要重写的函数。where子句只是告诉它仅在VideoTest为NSObject类型时才进行扩展

不管这是否有效,您实际上无论如何都不能这样做,因为扩展根本无法覆盖函数。请参阅swift文档了解扩展,尤其是这一点:

扩展可以向类型添加新功能,但不能 覆盖现有功能


我对Swift不太熟悉,但是如何观察(uquot:options:changeHandler:)
?请参阅中的键值观察?