So I decided to build ViewInspector, a library that allows for inspecting the SwiftUI view hierarchy at runtime.
And as it turned out, there were many pitfalls waiting for me on the way:
- All types in reflection are erased to
- Computed properties, such as
var body: some View, are not available in reflection
- Generic private structs and function types which are tricky to cast the value to
- Initializing a struct which all
initmethods are private
- SwiftUI dependency injection through
- Property wrappers, such as
@State, with an elusive storage for values
- Significant variations of the hierarchy after a tiny tweak of the input. For example,
- Overall obscurity and lack of information about the private structures
In this piece, I want to share abnormal use cases and hacky tricks I had to appeal to when building this library using just the standard capabilities of Swift language.