【问题标题】:Create a dictionary from a Codable struct with all CodingKeys and values从具有所有 CodingKey 和值的 Codable 结构创建字典
【发布时间】:2022-12-14 13:14:50
【问题描述】:

是否可以将Codablestruct中属性的存储值与所述属性的CodingKeys相关联,并在不手动配置每个结构的情况下返回它们?

我正在努力实现以下目标:

struct MyStruct: Codable {
    
    let propertyOne: String = "Value One"
    let propertyTwo: String = "Value Two"
    
    enum CodingKeys: String, CodingKey {
        case propertyOne = "Coding Key One"
        case propertyTwo = "Coding Key Two"
    }
    
    func allValues() -> [String: String] {

    /*
     
     return something like: [
        "Coding Key One": "Value One",
        "Coding Key Two": "Value Two"
     ]
     
     */

    }
}

使用Mirror() 没有多大帮助,因为它返回一个标签,该标签是属性的名称,如String,但我需要 CodingKey。并且 CaseIterable 没有获取存储属性的值。

先感谢您!

【问题讨论】:

    标签: swift codable


    【解决方案1】:

    你可以使用JSONSerialization来获取你的字典

    func allValues() throws -> [String: String] {
        let data = try JSONEncoder().encode(self)
        return try JSONSerialization.jsonObject(with: data) as? [String: String] ?? [:]
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多