【问题标题】:swift protocol extension with kvo使用 kvo 的 swift 协议扩展
【发布时间】:2018-01-10 19:29:15
【问题描述】:

我想创建一个具有默认 kvo 功能的协议。但是我有一个协议扩展继承 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 继承,是否可以通过协议扩展使用 KVO?

【问题讨论】:

标签: swift protocols avplayer key-value-observing


【解决方案1】:

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

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

注意

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多