[swift-users] How to cast within #keyPath() ?

Manfred Schubert dev at schubert-it.com
Tue Jul 25 11:16:48 CDT 2017


How can I cast a path segment within #keyPath() ? 

For example in the following code:

——

import Cocoa

class MyView: NSView {
    var property: String?
}

class MyViewController: NSViewController {
    
    var viewProperty: String? {
        return (view as! MyView).property                                    // 1)
    }
    
    override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
        var keyPaths = super.keyPathsForValuesAffectingValue(forKey: key)
    
        switch key {
        case #keyPath(viewProperty):
            keyPaths.formUnion(#keyPath(view.property))            // 2)
        default:
            break
        }
    
        return keyPaths
    }
}

——

In the line marked 1) I can cast view to MyView to access a property. In the line marked 2) I don't know how to perform that cast, and without I get the error "Type 'NSView' has no member 'property'".

How can I solve this problem?


Thanks,

Manfred


More information about the swift-users mailing list