Search code examples
iosswiftui

SwiftUI: Cannot find model in scope?


I have the following code:

@Observable class Car {
    var year:Int
    init(year:Int) {
        self.year = year
    }
}


struct CarView: View {
//    @State var model = Car(year: 1) // <-- works
    @Environment(Car.self) var model:Car // <-- Error: Cannot find '$model' in scope
    var body: some View {
        CarSubView(year: $model.year)
    }
}


struct CarSubView: View {
    @Binding var year:Int
    var body: some View {
        Button {
            year += year
        } label: {
            Text("TEST")
        }
    }
}

So I don't understand why I get the error Cannot find '$model' in scope when I use the @Environment(Car.self) var model:Car instead of @State var model = Car(year: 1).

I am passing the Car model via the environment and I was thinking I could then pass the year binding to the CarSubView.

How can I pass the year as binding to CarSubView when model comes to the view via environment?

Thank you


Solution

  • Change your CarView as follows:

    struct CarView: View {
        @Environment(Car.self) var model: Car
    
        var body: some View {
            @Bindable var model = model // <-- this is the key part
            CarSubView(year: $model.year)
        }
    }