1

I have a custom EnvironmentValue defined as:

private struct DataProviderKey: EnvironmentKey {
    static let defaultValue: DataProvider = {
        fatalError()
    }()
}

extension EnvironmentValues {
    var dataProvider: DataProvider {
        get {
            self[DataProviderKey.self]
        }
        set {
            self[DataProviderKey.self] = newValue
        }
    }
}

And main function looks like this:

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    var body: some Scene {
        WindowGroup {
            MyView()
                .environment(\.dataProvider, MyDataProvider())
        }
    }
}

My expectation is that the defaultValue won't be accessed as I inject the environment on App Launch. But before that happens, there's another call to the var dataProvider: DataProvider getter that I am not invoking.

Stack trace doesn't reveal much information as well: enter image description here

So my question is why is the getter being invoked by the system? Even if I remove the access with keyPath .environment(\.dataProvider, MyDataProvider()) it still gets called at the same point in time. I don't want to provide a default value because I want to know whenever such value is not injected immediately.

Pink
  • 521
  • 4
  • 13
  • "Why is the getter invoked by the system?" I would assume that the call to `.environment` populates some sort of hash table of environment values. This seems like expected behavior. – jnpdx Oct 28 '22 at 21:08

0 Answers0