Search code examples
swift4keypaths

Swift Keypath from String


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


Solution

  • 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)