I'm using the new Swift 4 KVO and KeyPath APIs to observe changes on an object. Specifically I'm trying to observe something on the selection object of an NSArrayController
. The problem is the selection
is of type Any
and that seems to be at odds with generating the required keypath, since the compiler doesn't know of any properties on an object of type Any
.
The property's name is assetPointHeight
. And my code looks like this:
var observation: NSKeyValueObservation?
observation = arrayController.observe(
#keyPath(NSArrayController.selection.assetPointHeight),
options: [.new],
changeHandler: { [weak self] (_, _) in
self?.updateLabel()
}
)
I get two compile errors:
Generic parameter
Value
could not be inferred
Type 'Any' has no member 'assetPointHeight'
How can I achieve what I'm looking for here? Is there another way of generating this KeyPath?
I would not expect this to work because assetPointHeight
isn’t a real property on selection
(eg, it’s not defined anywhere in source code, it’s a virtual property created at runtime). I think what’s happening here is the Swift 4 version of observe(...)
is trying to resolve that path to a static type and cannot, so it’s throwing an error. (Observing only works on NSObject
subclasses, as well, so Any
could never be observed.) So in this case you would have to use traditional string-based KVO, as “vadian” said.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With