Getting string from Swift 4 new key path syntax?

前端 未结 4 1951
别那么骄傲
别那么骄傲 2021-02-01 14:33

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

4条回答
  •  广开言路
    2021-02-01 14:54

    Short answer: you can't. The KeyPath abstraction is designed to encapsulate a potentially nested property key path from a given root type. As such, exporting a single String value might not make sense in the general case.

    For instance, should the hypothetically exported string be interpreted as a property of the root type or a member of one of its properties? At the very least a string array would need to be exported to address such scenarios...

    Per type workaround. Having said that, given that KeyPath conforms to the Equatable protocol, you can provide a custom, per type solution yourself. For instance:

    struct Auth {
        var email: String
        var password: String
    }
    struct User {
        var name: String
        var auth: Auth
    }
    

    provide an extension for User-based key 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")
        }
    }
    

    usage:

    let name:  KeyPath = \User.name
    let email: KeyPath = \User.auth.email
    print(name.stringValue)  /* name */
    print(email.stringValue) /* auth.email */
    

    I wouldn't really recommend this solution for production code, given the somewhat high maintenance, etc. But since you were curious this, at least, gives you a way forward ;)

提交回复
热议问题