Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe key path on 'Any' object in Swift 4

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?

like image 971
Mark Bridges Avatar asked Oct 14 '17 12:10

Mark Bridges


1 Answers

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.

like image 165
Wil Shipley Avatar answered Sep 28 '22 06:09

Wil Shipley