简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM