I want to write some generalized code that can write values to struct fields given the field name as a string. I've looked at various options and haven't settled on something I like yet.
-
WriteableKeyPath
doesn't seem to have a way to construct it from a string. -
Codable
obviously does something with string-based access (and the structs I'm working with are all codable), but it all happens behind the scenes. -
@objc
members could work, using good old KVC, but I keep running into cases that are not objc-compatible, like enums, and I don't want to let this string-based access feature dictate which data types I can use. -
Mirror
, at least in its public interface, only provides read access. The recent Swift Blog post How Mirror Works mentions the ability to "manipulate arbitrary values at runtime" but I didn't see how to actually do that.
The last option I'm considering is to have code that just looks up the fields using switch statements. Ideally, for best maintainability, I'd write something that processes the swift file, perhaps using SourceKit, and generates the accessor methods I would need.
Are there any other approaches to consider? Or is there a reason to recommend one of the things I already looked at?