sideshowbob
sideshowbob

Reputation: 316

swift protocol extension with kvo

I want to create a protocol that has default kvo functionality. However I am having issues having a protocol extension inherit NSObject. When I try to override observeValue(forKeyPath I get an error Method does not override any method from its superclass. Here is some sample code of what I am trying to do

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?) {

     }

}

Is it possible to be able to use KVO via a protocol extension since I can't directly inherit from NSObject?

Upvotes: 1

Views: 510

Answers (1)

Upholder Of Truth
Upholder Of Truth

Reputation: 4711

This is because the compiler looks for the function you are overriding on the VideoTest protocol itself. The where clause is just telling it to only do the extension when the VideoTest is of the NSObject type.

Regardless of whether this did work or not you can't actually do this anyway because extensions cannot override functions at all. See the swift documentation for extensions here particularly this bit:

NOTE

Extensions can add new functionality to a type, but they cannot override existing functionality.

Upvotes: 1

Related Questions