So I do think this pitch proposal has some good ideas overall worth discussing. But for this specific SwiftUI example I am not sure that trying to read from Environmentbefore computing a view component body is ever officially supported. If the assumption is this "lazy" variable is only read at the time a view component body is computed then maybe it looks safe… but still feels a little "brittle" to me.
I would offer another solution built on DynamicProperty and update which is explicitly documented to run before our view component body is computed:
@Observable
final class Storage {
private var modelContext: ModelContext? = nil
init() {
}
func update(modelContext: ModelContext) {
if self.modelContext !== modelContext {
self.modelContext = modelContext
...
}
}
}
struct ViewModel: DynamicProperty {
@Environment(\.modelContext) private var modelContext
@State private var storage = Storage()
func update() {
self.storage.update(modelContext: self.modelContext)
}
}