How to use MVVM with SwiftUI correctly?

Viewed 157

I'm currently learning about the use of MVVM and SwiftUI, and I was wondering, are the View allowed to pass Model objects to the ViewModel?

Example:

At one point while I was coding, I needed to use one variable from an object in a view, So i created a ViewModel to only pass that one variable, by doing something like this:

struct ListRowView: View {

    @ObservedObject var viewModel: ViewModel = ViewModel()
    let modelData: ModelData;

    var body: some View {
        HStack {
            Text(viewModel.name)
        }.onAppear() {
            self.viewModel.fetchData(modelData: self.modelData)
        }
    }
}

class ViewModel: ObservableObject {

    @Published var title = "";

    func fetchData(modelData: ModelData){
        self.title = modelData.title;
    }
}

Is this the correct way of using MVVM and SwiftUI? Because in this example the view technacly handles a Model object by passing it to the ViewModel? Is this "okay?" or is other solutions better? and in that case, which?

0 Answers
Related