Home > Net >  How do I get a "Binding" from my model to my View in Swift?
How do I get a "Binding" from my model to my View in Swift?

Time:06-21

I'm fairly new to Swift and I'm already running problems. From my understanding, it is good practice to split the app into Models that describe the data, Views that display stuff and allow for user input, and ViewModels that translate the user's intents into data modification and allows the view to react accordingly.

That being said, I set out on doing a very simple app using that logic. So I create a model file that goes like:

import Foundation

struct MyModel {
    var testData: Double
    ...
}

then a viewModel that looks like this;

import Foundation

class MyViewModel: ObservableObject {
    @Published var myModel = MyModel(testData: 0)

    func setTest(_ newVal: Double) {
        splitModel.testData = newVal
    }

    ...
}

and finally my view:

struct ContentView: View {
    @ObservedObject var viewModel = MyViewModel()

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Hello", value: viewModel.splitModel.amount, format: .currency(code: "USD"))
                }
            }
        }
    }
}

And this doesn't work because viewModel.splitModel.amount isn't a Binding but a straight up Double. The only way I found to fix that is to just put the data in the view with @State, so exactly what I was trying to avoid by getting this file structure.

I would love an explanation of the logic I'm supposed to implement to make it work, and maybe get corrected about my comprehension of Swift. Thanks in advance !

CodePudding user response:

You can use the $ sign to refer to the binding.

TextField("Hello", value: $viewModel.splitModel.amount, format: .currency(code: "USD"))

Also dont´t use @ObservedObject here use @StateObject. @ObservedObject should only be used if the view does not initialize the viewmodel and it is injected.

  • Related