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)
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 ...
which would vary in your use case.