Björn
Björn

Reputation: 370

SwiftUI View and ViewModel Modifying with Binding and Observed variables

I have a View and a ViewModel and would like to set some variables in the ViewModel and read AND set them in the View. In the ViewModel I have a @Published variable. When I try to modify the value of the variable in the View, the errors I get are: 'Cannot assign to property: '$testModel' is immutable' and 'Cannot assign value of type 'String' to type 'Binding'. Is there a way to do this? The code I have now is as follows:

View

struct TestView: View {

@ObservedObject var testModel: TestViewModel = TestViewModel()

var body: some View {
    VStack(alignment: .center, spacing: 4) {
        
        Button(action: {
            $testModel.test = "test2"
        }) {
            Text("[ Set value ]")
            }
        }
    }
}

ViewModel

class TestViewModel: ObservableObject {

    @Published var test = "test"

}

Upvotes: 1

Views: 1225

Answers (1)

George
George

Reputation: 30451

Since you don't need the Binding to set the value, you don't need $testModel, just testModel.

Change code to this:

Button(action: {
    testModel.test = "test2"
}) {
    Text("[ Set value ]")
}

It's also worth noting that you should use @StateObject rather than @ObservedObject here to prevent TestViewModel potentially being initialized multiple times.

Upvotes: 2

Related Questions