[英]Nested Swift 4 Codable Struct uses CodingKeys irregularly
[英]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.