【问题标题】:Swift: custom key-value encoding with Encodable conformance in structSwift:在结构中具有 Encodable 一致性的自定义键值编码
【发布时间】:2020-07-23 16:42:15
【问题描述】:
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 以得到这个结果?

【问题讨论】:

    标签: json swift encodable


    【解决方案1】:

    实现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])
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 2019-03-13
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多