繁体   English   中英

从具有所有 CodingKey 和值的 Codable 结构创建字典

[英]Create a dictionary from a Codable struct with all CodingKeys and values

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

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

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不获取存储属性的值。

先感谢您!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM