我所拥有的:具有不同属性的可编码结构。
我想要的:一个函数,当它以 Json 编码时,我可以在其中获取属性的确切名称。我认为最有前途的方法是使用 Keypath,但我不知道如何以及是否可能。谢谢!
我所拥有的:具有不同属性的可编码结构。
我想要的:一个函数,当它以 Json 编码时,我可以在其中获取属性的确切名称。我认为最有前途的方法是使用 Keypath,但我不知道如何以及是否可能。谢谢!
没有办法开箱即用,因为Codable
类型的属性与其编码键之间没有 1-1 映射,因为可能存在不属于编码模型的属性或依赖于多个编码的属性键。
但是,您应该能够通过定义属性与其编码键之间的映射来实现您的目标。你在正确的轨道上使用KeyPath
s,你只需要定义一个函数,它KeyPath
的根类型是你的可编码模型,并从所述函数返回编码密钥。
struct MyCodable: Codable {
let id: Int
let name: String
// This property isn't part of the JSON
var description: String {
"\(id) \(name)"
}
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "identifier"
}
static func codingKey<Value>(for keyPath: KeyPath<MyCodable, Value>) -> String? {
let codingKey: CodingKeys
switch keyPath {
case \MyCodable.id:
codingKey = .id
case \MyCodable.name:
codingKey = .name
default: // handle properties that aren't encoded
return nil
}
return codingKey.rawValue
}
}
MyCodable.codingKey(for: \.id)