Using Swift 4, I don’t think you can automatically extract CodingKey
from the corresponding object KeyPath
, but you can always hack it;)
For example, in the same source file of User
type 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 CodingKey
in a restricted KeyPath
superclass:
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.)