Search code examples
swiftreflectionswift4key-value-coding

Getting string from Swift 4 new key path syntax?


How can you get a string value from Swift 4 smart keypaths syntax (e.g., \Foo.bar)? At this point I'm curious about any way at all, does not matter if it's complicated.

I like the idea of type information being associated with smart key path. But not all APIs and 3rd parties are there yet.

There's old way of getting string for property name with compile-time validation by #keyPath(). With Swift 4 to use #keyPath() you have to declare a property as @objc, which is something I'd prefer to avoid.


Solution

  • For Objective-C properties on Objective-C classes, you can use the _kvcKeyPathString property to get it.

    However, Swift key paths may not have String equivalents. It is a stated objective of Swift key paths that they do not require field names to be included in the executable. It's possible that a key path could be represented as a sequence of offsets of fields to get, or closures to call on an object.

    Of course, this directly conflicts with your own objective of avoiding to declare properties @objc. I believe that there is no built-in facility to do what you want to do.