2

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)!]
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Rodrigo Ruiz
  • 4,248
  • 6
  • 43
  • 75
  • Can you give some more context here? It isn't really clear what you are trying to achieve. Does the string you are trying to convert have a specific format, or is it arbitrary? – oyvindhauge Oct 02 '17 at 12:40
  • @ØyvindHauge I edited the question to be more specific. – Rodrigo Ruiz Oct 02 '17 at 17:19

1 Answers1

1

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.

Chris Garrett
  • 4,824
  • 1
  • 34
  • 49