例如,我有可编码的结构User
:
struct User: Codable {
// ...
var psnTag: String?
var xblTag: String?
var steamTag: String?
var nintendoTag: String?
var instagramId: String?
// ...
}
和stringKey为String
=“ psnTag”
如何通过stringKey从实例获取值?
赞:
let stringKey = "psnTag"
user.hasKeyForPath(stringKey) //return Bool
user.valueForPath(stringKey) //return AnyObject
答案 0 :(得分:0)
从扩展Encodable
协议开始,并声明hasKey
和value
的方法
extension Encodable {
func hasKey(for path: String) -> Bool {
return Mirror(reflecting: self).children.contains { $0.label == path }
}
func value(for path: String) -> Any? {
return Mirror(reflecting: self).children.first { $0.label == path }?.value
}
}
extension Encodable {
func hasKey(for path: String) -> Bool {
return dictionary?[path] != nil
}
func value(for path: String) -> Any? {
return dictionary?[path]
}
var dictionary: [String: Any]? {
return (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: Any]
}
}
现在您可以像这样使用它:
.hasKey(for: "key") //returns Bool
.value(for: "key") //returns Any?