Short answer: you cannot. The KeyPath abstraction KeyPath intended to encapsulate a potentially nested property key path from a given root type. Thus, exporting a single String value may not make sense in the general case.
For example, should a hypothetical exported string be interpreted as a property of the root type or a member of one of its properties? At least an array of strings should be exported to solve such scenarios ...
Workaround for each type . Having said that, given that KeyPath conforms to the Equatable protocol, you can independently create your own solution for each type. For example:
struct Auth { var email: String var password: String } struct User { var name: String var auth: Auth }
provide an extension for User main paths:
extension PartialKeyPath where Root == User { var stringValue: String { switch self { case \User.name: return "name" case \User.auth: return "auth" case \User.auth.email: return "auth.email" case \User.auth.password: return "auth.password" default: fatalError("Unexpected key path") } }
using:
let name: KeyPath<User, String> = \User.name let email: KeyPath<User, String> = \User.auth.email print(name.stringValue) /* name */ print(email.stringValue) /* auth.email */
I would not recommend this solution for production code, given the somewhat high level of service, etc. But since you were curious that this at least gives you a way forward;)
Paulo mattos
source share