1

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"

}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.