簡體   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