Search code examples
iosswiftswiftuiobservableobject

SwiftUI optional state variable binding with if let


The code below does not build. How do I make it work?

import SwiftUI

struct TestView: View {
    
    @State var model:TestModel?
    
    var body: some View {
        
        if let model = model {
            OverlayTestView(textVM: model) 
//Error: Cannot convert value of type 'TestModel' to expected argument type 'Binding<TestModel>'
        } else {
            ProgressView()
                .task {
                    model = TestModel()
                }
        }
       
            
    }
}

struct OverlayTestView: View {
    @Binding var textVM:TestModel
    
    var body:some View {
        Text("Count \(textVM.counter)")
    }
}

@Observable
class TestModel {
    var counter:Int = 0
}
 

Solution

  • Change @Binding to @Bindable, @Binding is for value types