Get specific code for KeyPath

Consider the following object:

struct User: Codable {
    let id: Int
    let email: String
    let name: String
}

Is it possible to get specific CodingKeyfor a given KeyPath?

let key = \User.name.codingKey  // would be equal to string: "name"
+4
source share
2 answers

Using Swift 4, I don’t think you can automatically extract CodingKeyfrom the corresponding object KeyPath, but you can always hack it;)

For example, in the same source file of Usertype Swift type, add the following extension:

fileprivate extension User {
    static func codingKey(for keyPath: PartialKeyPath<User>) -> CodingKey {
        switch keyPath {
        case \User.id:    return CodingKeys.id
        case \User.email: return CodingKeys.email
        case \User.name:  return CodingKeys.name
        default: fatalError("Unexpected User key path: \(keyPath)")
        }
    }
}

then implement the desired API CodingKeyin a restricted KeyPathsuperclass:

extension PartialKeyPath where Root == User {
    var codingKey: CodingKey {
        return User.codingKey(for: self)
    }
}

Finally, use closely monitors your code:

let name: CodingKey = (\User.name).codingKey
print("\(name)") // prints "name"

, , , , , ;)

. , , CodingKeys enum private . (, Codable, Swift.)

+1

, , , , :

let user = User(id: 1, email: "sample@email.com", name: "just_name")
Mirror(reflecting: user).children.first?.label
-2

Source: https://habr.com/ru/post/1686719/


All Articles