![](/img/trans.png)
[英]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.