Property wrappers and SwiftUI environment: how can @FetchRequest work?


I discover the existence of the @FetchRequest property wrapper that ships with Core Data.

It helps declaring properties that are auto-updated whenever the core data storage changes. You only have to provide a fetch request:

struct MyView: View {
    @FetchRequest(fetchRequest: /* some fetch request */)
    var myValues: FetchedResults<MyValue>

The fetch request can't access the storage without a managed object context. This context has to be passed in the view's environment.

And now I'm quite puzzled.

How can a property wrapper access the environment of its enclosing object?

Cross-posted on Stack Overflow.

Hmmm. I guess it is not the property wrapper that accesses the environment of its enclosing object. Instead, SwiftUI injects the environment in the wrapper. But how?

FetchRequest only declares conformance to DynamicProperty, a protocol that still doesn't solve this mystery.

Terms of Service

Privacy Policy

Cookie Policy