We don't know the exact internals of how SwiftUI is implemented, but we can make some educated guesses based on the information we have available.
First, @propertyWrapper
s do not get automatic access to any kind of context from their containing struct/class. You can check out the spec for evidence of that. This was discussed a few times during the evolution process, but not accepted.
Therefore, we know that something has to happen at runtime for the framework to inject the @EnvironmentObject
(here the NSManagedObjectContext
) into the @FetchRequest
. For an example of how to do something like that via the Mirror
API, you can see my answer in this question. (By the way, that was written before @Property
was available, so the specific example is no longer useful).
However, this article suggests a sample implementation of @State
and speculates (based on
an assembly dump) that rather than using the Mirror API, SwiftUI is using TypeMetadata for speed:
Reflection without Mirror
There is still a way to get fields without using Mirror. It's using metadata.
Metadata has Field Descriptor which contains accessors for fields of the type. It's possible to get fields by using it.
My various experiments result AttributeGraph.framework uses metadata internally. AttributeGraph.framework is a private framework that SwiftUI use internally for constructing ViewGraph.
You can see it by the symbols of the framework.
$ nm /System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
There is AG::swift::metadata_visitor::visit_field in the list of symbols. i didn't analysis the whole of assembly code but the name implies that AttributeGraph use visitor pattern to parse metadata.