Swift: 自定义键值编码,在结构中符合 Encodable
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])
}
}
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])
}
}