I am struggling to use the new strongly-typed KVO syntax in Swift 4 to observe properties that are only visible through a 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, Observable
is not an NSObject
. But I cannot simply cast it to NSObject
, because the type of the keypath will not match the type of the object.
I tried being more explicit about the type:
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
Is what I am trying to do not possible? This seems a common use case. It is easily done with old #keypath syntax. Can you offer any alternatives? Thanks.