SE-0064 Property Selectors and KVO


(Rob Napier) #1

Currently KVO requires hard-coding strings to check the keypath. Does
SE-0064 cover returning a string when a string is required? For example:

override func observeValueForKeyPath(keyPath: String?,

                                     ofObject object: AnyObject?,

                                     change: [String : AnyObject]?,

                                     context: UnsafeMutablePointer<Void>) {

    if let changingThing = object as? Thing,

           keyPath = keyPath where changingThing === thing {

        switch keyPath {

        case "thingWatched": ...

I'd like to replace that last line with:

        case #selector(Thing.thingWatched):

Or something similarly non-stringy.

Alternately, this comes back to your "Referencing Objective-C key-paths"
proposal, but I'm wondering if 0064 already covers this case.

-Rob


(David Hart) #2

#selector(Thing.thingWatched) won't work because it expects a function. As thingWatched is a property, it doesn't know if you want to reference the getter or setter. SE-0064 lets you reference those explicitly. In this case, you could write NSStringFromSelector(#selector(getter: Thing.thingWatched)), which is far from elegant. SE-0062 is there to fix that: #keyPath(Thing.thingWatched) will return the correct string.

···

Sent from my iPhone

On 04 Jun 2016, at 16:18, Rob Napier <robnapier@gmail.com> wrote:

Currently KVO requires hard-coding strings to check the keypath. Does SE-0064 cover returning a string when a string is required? For example:

override func observeValueForKeyPath(keyPath: String?,
                                     ofObject object: AnyObject?,
                                     change: [String : AnyObject]?,
                                     context: UnsafeMutablePointer<Void>) {
    if let changingThing = object as? Thing,
           keyPath = keyPath where changingThing === thing {

        switch keyPath {
        case "thingWatched": ...

I'd like to replace that last line with:

        case #selector(Thing.thingWatched):

Or something similarly non-stringy.

Alternately, this comes back to your "Referencing Objective-C key-paths" proposal, but I'm wondering if 0064 already covers this case.

-Rob