可编码结构:通过键获取价值

时间:2018-12-22 21:11:22

标签: swift key-value-coding

例如,我有可编码的结构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

1 个答案:

答案 0 :(得分:0)

从扩展Encodable协议开始,并声明hasKeyvalue的方法

使用镜子

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
    }
}

使用JSON序列化

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?