4

Is there a way to create a Keypath from a String in Swift 4 to access a value in a struct by its path or variable name

Finally I found out that I should use CodingKeys instead of KeyPaths to access the a value of a variable of a struct by String

Thanks in advance, Michael

Michael_mhr
  • 744
  • 1
  • 9
  • 27

1 Answers1

-1

consider you have something like this,

struct foo {

var test: doo

}

struct doo {

var test: Int

}
 //How to use it 

    let doo = Doo(test: 10)
    let foo = Foo(test: doo)

    let mykeyPath = \Foo.test.test

    let result = foo[keyPath: mykeyPath]

    print(result)
Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • Is there I way to get the KeyPath from String to make it runtime-configurable? – Michael_mhr Sep 20 '18 at 15:35
  • this is how to use keypath with structs so any value changing the keypath accessing remain the same i don't really understand what you mean by "KeyPath from String to make it runtime-configurable" – Mohmmad S Sep 20 '18 at 15:37
  • I want to create a KeyPath from String. For example the String contains 'sensors.temperature.temp1' I will get the (Optional) value of the variable in the nested struct with the name 'temp1' – Michael_mhr Sep 20 '18 at 15:42
  • Coding Keys ? thats something else – Mohmmad S Sep 20 '18 at 15:43
  • edit your question add the structs and be clear KeyPath, is not Coding Keys , if you are trying to access something with KeyPath thats how thats the correct answer if you want to decode something into another things using structs thats called Coding Keys – Mohmmad S Sep 20 '18 at 15:45
  • try the code above, in your case make sure to understand it too – Mohmmad S Sep 20 '18 at 15:46
  • I haven't heard about CodingKeys and searched for KeyPath instead... I will close this question, because there are already many questions to this thematic out there. Thank you very much for your time answering this senseless question.. – Michael_mhr Sep 20 '18 at 15:53
  • Would you close or delete it? – Michael_mhr Sep 20 '18 at 15:54
  • i would leave it, other people may find it helpful :) either the answer or the question, personally i marked as fav – Mohmmad S Sep 20 '18 at 15:56