Search code examples
iosswiftmvvmreferenceviewcontroller

Swift MVVM, a ViewController without a ViewModel reference?


I've been wondering if it was possible to have a MVVM architecture with no reference of the ViewModel in the ViewController, I understand that it needs this reference because ViewModel works as a DataContext but I'm trying to figure it out, I want to isolate as much as possible responsibilities and dependency injection between Views and ViewModel. Have you any idea on how it is possible to achieve that in a MVVM pattern in Swift?


Solution

  • Let`s have a look your ideas step by step in MVVM aspects

    "No reference of ViewModel in the ViewController or View."

    It is not a good idea. By referencing to viewmodel in your view you notify viewmodel. That does not mean you need to do logic in your view or viewcontroller.

    "I want to isolate as much as possible responsibilities and dependency injection between Views and ViewModel."

    Exactly! ViewModel handle the all logic. View needs to be lightweight and no logic. There are many approaches in terms of binding your view to viewmodel and separating concerns. I can give an example below.


    Move your datasource from view to viewmodel. For example if you working a tableviewdatasource then make a generic datasource( you can find many examples by google ) for your tableViewDataSource. Your viewcontroller will be something like below:

    private var dataSource : YourTableViewDataSource<YourData>!
    private var yourViewModel: YourViewModel!
    
    self.yourTableViewDataSource = dataSource
    func updateDataSource() { }