Hi all. I have used Mirror a few times and it works well enough but to create, and get/set values is cludgy. I have used key paths and other approaches and wondering is there either a SPM that exists to help, or when will Swift get full featured reflection ? Thank you.
Getting values via Mirror
API is ok-ish, but set? Is that possible at all? I thought not.
Actually, you can get and set values, but it's not perfect. Setting using Generics and other approaches is not simple.
The existing Mirror facility is quite limited unfortunately.
A better API to access the existing reflection metadata is possible, though. It should look at a metatype, instead of a specific value of the type like Mirror does. For example, you should be able to ask a struct metatype for its fields, an enum for its cases, and take apart function and tuple metatypes as well. Then we could implement mutation on top of this by dynamically constructing keypaths, perhaps.
Could you show an example how to use set with mirror API?
"get" is simple:
struct S { var x = 42 }
var s = S()
print(Mirror(reflecting: s).children.first!.value) // 42
Would like to know this too! I assumed @pkasson was referring to values that are mutable reference types.
A while ago I've implemented a library providing easy access to Swift's extensive runtime metadata, which allows reading and writing stored properties in structs, enums, and actors, as well as members in tuples in a type-safe way.
It's by no means complete (as @Slava_Pestov said, there's a lot more you can do like inspect enum cases and decompose functions), but it's a place to start.
The mutating access is done using closures, because I couldn't figure out how to safely construct key paths dynamically within the limited time I had to research them.
Pull requests are very welcome! I implemented it while obsessing over reverse-engineering SwiftUI's data flow mechanism.
I just realized that I haven't provided the link to the implementation