[英]Create a dictionary from a Codable struct with all CodingKeys and values
Is it possible to associate the stored values of properties in a Codable
struct
with the CodingKeys
of said properties, and return them without manual configuration of each struct?是否可以将
CodingKeys
struct
中属性的存储值与所述属性的Codable
相关联,并在不手动配置每个结构的情况下返回它们?
I am trying to achieve the following:我正在努力实现以下目标:
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"
]
*/
}
}
Using Mirror()
doesn't help much because it returns a label which is the property's name as a String
, but I require the CodingKey.使用
Mirror()
并没有太大帮助,因为它返回一个标签,该标签是作为String
的属性名称,但我需要 CodingKey。 And CaseIterable
doesn't get the values of the stored properties.并且
CaseIterable
不获取存储属性的值。
Thank you in advance!先感谢您!
You could use JSONSerialization
to get your dictionary你可以使用
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.