KVObserving protocol in Swift 4

I am trying to use the new strongly typed KVO syntax in Swift 4 to observe properties that are visible only through the protocol:

import Cocoa

@objc protocol Observable: class {
    var bar: Int { get }
}

@objc class Foo: NSObject, Observable {
    @objc dynamic var bar = 42
}

let implementation = Foo()

let observable: Observable = implementation

let observation = observable.observe(\.bar, options: .new) { _, change in
    guard let newValue = change.newValue else { return }

    print(newValue)
}

implementation.bar = 50

error: value of type 'Observable' has no member 'observe'
let observation = observable.observe(\.bar, options: .new) { _, change in

Clearly that is Observablenot NSObject. But I can’t just pass it in NSObject, because the type of the path to the keys will not match the type of the object.

I tried to describe the type in more detail:

let observable: NSObject & Observable = implementation

But:

error: member 'observe' cannot be used on value of protocol type 'NSObject & Observable'; use a generic constraint instead
let observation = observable.observe(\.bar, options: .new) { _, change in

Am I trying to do what I can’t? This seems like a common use case. This is easy to do with the old #keypath syntax. Can you suggest any alternatives? Thank.

+4
source share

Source: https://habr.com/ru/post/1688997/


All Articles