![](/img/trans.png)
[英]Swift and Codable: Encodable tree struct terminating in values that obey custom protocol
[英]Swift: custom key-value encoding with Encodable conformance in struct
struct Struct: Encodable {
let key: String
let value: String
}
let aStruct = Struct(key: "abc", value: "xyz")
鑒於此結構和提供的默認Encodable
一致性,JSON 編碼產生
{
key = abc;
value = xyz;
}
而相反,我想將其編碼為
{
abc = xyz;
}
我如何使這個結構符合Encodable
以得到這個結果?
實現encode(to encoder: Encoder)
並將結構編碼為單個字典
struct Struct: Encodable {
let key: String
let value: String
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode([key:value])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.