【发布时间】:2023-04-10 07:18:02
【问题描述】:
假设我有一个 struct User 模型,其中包含许多属性。
struct User: Codable {
let firstName: String
let lastName: String
// many more properties...
}
正如您在上面看到的,它符合Codable。想象一下,如果 lastName 属性应该被编码/解码为 secondName 并且我想在最后将其保留为 lastName,我需要将 CodingKeys 添加到 User 模型中。
struct User: Codable {
//...
private enum CodingKeys: String, CodingKey {
case firstName
case lastName = "secondName"
// all the other cases...
}
}
是否有任何可能的方法来避免在CodingKeys 中包含与rawValue 具有相同值的所有cases,就像上面示例中的firstName 一样(感觉多余)?我知道如果我避免在CodingKeys 中使用cases,它将不会在解码/编码时包含在内。但是,有没有办法可以覆盖这种行为?
【问题讨论】:
-
让我知道如果我不够清楚或者这是重复的,我只能找到说明如何排除不必要(编码/解码时不需要)键的那个。
-
您从过去 2 天开始没有参与 :p 一切都好吗?
标签: swift codable jsondecoder jsonencoder