How do I convert a String
to a WritableKeyPath
?
Something like:
struct MyStruct {
let x: Bool
}
let string = "x"
let myStruct = MyStruct(x: false)
let x = myStruct[keyPath: keyPathFromString(string)!]
How do I convert a String
to a WritableKeyPath
?
Something like:
struct MyStruct {
let x: Bool
}
let string = "x"
let myStruct = MyStruct(x: false)
let x = myStruct[keyPath: keyPathFromString(string)!]
There is no way to do this. The reason behind this is that Swift is doing its best to try to give us "dynamic-like" features in the language, while still providing compile-time checking for key paths. If they were to allow conversion of a String to a key path, then the key path would be determined at runtime instead of compile time.
You asked a perfectly valid question, so I recommend asking a new question that is a more specific use case in what you are trying to achieve. Even though key paths are limited to compile time, they are still a powerful language feature and there may be a way to do what you want using them or another Swift 4 feature such as the new Codable protocol.