How do You Convert an AnyKeyPath to a WritableKeyPath?

一世执手 提交于 2019-12-05 12:55:04
RicardoDuarte

After a few hours playing around with code, the best I got was this:

struct Person {
var name: String
var collection: [String]
var optionalCollection: [String]?
let birthdate: Date

fileprivate func keyPath<V>(from label: String, type: V.Type) -> WritableKeyPath<Person, V> {
    print("type: \(type)")
    let valuePair: [String: PartialKeyPath<Person>] = ["name": \Person.name,
                                                       "birthdate": \Person.birthdate,
                                                       "collection": \Person.collection,
                                                       "optionalCollection": \Person.optionalCollection]
    return valuePair[label] as! WritableKeyPath<Person, V>
}


}



var person = Person(name: "john",
                    collection: [],
                    optionalCollection: ["gotcha"],
                    birthdate: Date(timeIntervalSince1970: 0))


let name = person[keyPath: person.keyPath(from: "name", type: String.self)] // john
let birthdate = person[keyPath: person.keyPath(from: "birthdate", type: Date.self)] // Jan 1, 1970
let collection = person[keyPath: person.keyPath(from: "collection", type: Array<String>.self)] // []
let optionalCollection = person[keyPath: person.keyPath(from: "optionalCollection", type: Optional<Array<String>>.self)] // ["gotcha"]

However you must always pass the type as parameter. If only the Mirror class allowed us to get the actual type from each property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!