Swift Keypath from String

4.1k Views Asked by At

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

1

There are 1 best solutions below

9
On BEST ANSWER

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)