Search code examples
iosswiftswift4

How do I use #keyPath() in Swift 4?


I think part of my problem is because Swift 4 has changed the way things like @objc work.

There are a lot of tutorials floating around, with a lot of different values, and I can't pick my way between what used to work in what version enough to figure out how to make it work in this version.

let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.addObserver(self, forKeyPath: #keyPath(AppDelegate.session), options: [], context: nil)
// Warning: Argument of #keyPath refers to non-'@objc' property 'session'

Adding @objc to the var declaration just informs me that APISession can't be referenced in Objective-C. That seems to lead down the path towards requiring me to expose every class / variable I want to use this tool with to Obj-C, and that just seems backwards -- this is a newer feature, as I understand it, and it's just odd that Apple wouldn't make it work natively in Swift. Which, to me, suggests I'm misunderstanding or misapplying something, somewhere, somehow.


Solution

  • According to the docs:

    In Objective-C, a key is a string that identifies a specific property of an object. A key path is a string of dot-separated keys that specifies a sequence of object properties to traverse.

    Significantly, the discussion of #keyPath is found in a section titled "Interacting with Objective-C APIs". KVO and KVC are Objective-C features.

    All the examples in the docs show Swift classes which inherit from NSObject.

    Finally, when you type #keyPath in Xcode, the autocomplete tells you it is expecting an @objc property sequence.

    enter image description here

    Expressions entered using #keyPath will be checked by the compiler (good!), but this doesn't remove the dependency on Objective-C.