I see the exact same behavior. And the defaultValue is even computed when the Environment is overridden with a new value.
This simple app:
import SwiftUI
struct SomeValue {
init() {
print("SomeValue.init()")
}
}
extension EnvironmentValues {
@Entry var someValue: SomeValue = SomeValue()
}
struct ContentView: View {
@Environment(\.someValue) private var someValue
var body: some View {
VStack {
Text("Hello, world!")
}
.padding()
}
}
@main
struct MyAppApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.someValue, SomeValue())
}
}
}
Will print the following:
SomeValue.init()
SomeValue.init()
SomeValue.init()
SomeValue.init()
And if you put a break point inside the initializer of SomeValue, you will notice that the first time SomeValue is initialized is when it is passed to the .environment() modifier. The succeeding three times is from when the defaultValue is computed.
Even without the use of the Entry macro, the defaultValue is always called/computed even if the value has been explicitly set with the .environment() modifier before it is ever being used.
Though this might be completely by design, it is a bit unexpected (to me at least).
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: