Can AnyKeyPath be extended to provide a path String?


(Adrian Zubarev) #1

I wonder if it would be possible to extend AnyKeyPath with a property that returns key-path as a string. Right now there is this hidden hook but it is not guaranteed to return the path at all as the return type is optional:

It also has has a different representation than the actual key-path might look in code.

For example the following two key-paths from a UIViewController:

\.view.isOpaque
\.view.isHidden

Will produce the values Optional("view.opaque") and Optional("view.hidden"). However I would wish for a simple property like var keyPathString: StaticString/String { get } that returns "view.isOpaque" and "view.isHidden".


(Brent Royal-Gordon) #2

What do you want to do with the string?


#3

My understanding is that it is a conscious design decision to not include these strings, as it can reveal details about the inner workings of your program, which is a downside of Objective-C for several users.


(Adrian Zubarev) #4

I would like to hash a custom type, keyed by a string, created using a key-path by also avoiding collisions.

Right now I'm abusing hashValue as it's the only value that provides some sort of uniqueness.
I'm doing something like this "\(Root.self).\(keyPath).\(keypath.hashValue)". (Edit) I worked around this problem actually, but the main question remains.

Can/should we extend AnyKeyPath with such property in the future?


(Jordan Rose) #5

Key paths are already unique (and Hashable) themselves.

Not every key path has a string representation; only those that represent Objective-C properties. So this isn't doable in the general case (unless we start putting a lot more metadata into binaries).