swift 从Codable结构创建一个包含所有CodingKey和值的字典

pcww981p  于 2022-12-17  发布在  Swift
关注(0)|答案(1)|浏览(141)

是否可以将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不获取存储的属性的值。
先谢谢你!

vzgqcmou

vzgqcmou1#

您可以使用JSONSerialization来获取字典

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

相关问题