Learn Courses My Dashboard

Monthly App Challenge - problems binding variable in viewmodel to UI element

I’ve created a weather model which includes a @Published var called metricSelected:

    @Published var metricSelected = true

I’m having problems binding this to a toggle UI element. I am able to reference the variable in my View - for example with:

        HStack {
            Text("Feels like ")
            if model.metricSelected {
                Text("\(String(format: "%.0f", model.feelsLike!))")
            } else {
                Text("\(String(format: "%.0f", model.convertToFarenheit(model.feelsLike!)))")
                Text(model.metricSelected ? "C" : "F")


But if I use this code for a Toggle element - I get an error: “Cannot convert value of type ‘Bool’ to expected argument type ‘Binding’”

        Toggle(isOn: model.$metricSelected) {

I’ve created a really cronky workaround (which works) but I am sure is not the right way. I’ve added a @State var declaration with a new variable called myViewMetricSelected to the view, and then used this to reset the variable in the viewModel:

        Toggle(isOn: $myViewMetricSelected) {
        }.onChange(of: myViewMetricSelected, perform: { value in

Advice would be greatly welcomed! Have been struggling with this for a bit now…

Toggle(isOn: model.$metricSelected) {

should be

Toggle(isOn: $model.metricSelected) {
1 Like

Thank you! Greatly appreciated!