swiftcodableswift-structs

Swift 5.7, can you use a string to dynamically use a keyPath with Structs?


struct Server: Codable {
 let cats: Int
 let dogs: Int
 let fishies: Int
}

It must be Codable.

let x = Server(cats: 42, dogs: 13, fishes: 777)

We can use keypaths:

print( x[keyPath: \.dogs] )

Which would print "13".

Is there a way to use a string for the keypath? So, something like

let str = ".dogs"
print( x[ keyPath: \$str ] ]

or perhaps

let s = ".dogs"
let k = KeyPath(fromString: s)
print( x[keyPath: k] )

(Note, I appreciate there are any number of other approaches, eg, use sql, dictionaries, switch statement, etc etc. The question at hand is as stated, TY)


Solution

  • Swift 5.7, can you use a string to dynamically use a keyPath with Structs?

    For the record, the answer is No, you cannot, as of Swift5.


    If you need to access struct fields, by string (for example in a typical "column definition" setup), just IMO the best thing to do is simply something like ...

    func structField(viaString key: String) -> String {
        switch key {
        case "height": return String(self.height)
        case "lat": return self.lat
        case "long": return self.long
        ... etc
        ... etc
    

    which would vary in your use case.