iosswiftinheritancemvvmcoordinator-pattern

iOS: MVVM-C ViewController super class


I have MVVM-C arch. Each UIViewController has a ViewModel and CoordinatorDelegate to notify the Coordinator when navigation needs to be performed. The code that creates the VC repeats itself, and I thought it would be great to create a super class to unify all static funcs that create the VC. Like this:

import UIKit

class MVVMCViewController: UIViewController {
    
    weak var coordinatorDelegate: CoordinatorDelegate?
    var viewModel: Modelling?
    
    static func initVC(storyboard: Storyboard,
                       coordinatorDelegate: CoordinatorDelegate?,
                       viewModel: Modelling?) -> Self {
        let viewController = Self.instantiate(in: storyboard)
        viewController.coordinatorDelegate = coordinatorDelegate
        viewController.viewModel = viewModel
        return viewController
    }
}

All CoordinatorDelegateProtocols will inherit from CoordinatorDelegate and all ViewModels will be inheriting from Modelling.

But the subclassing does not work smoothly.

enter image description here

Any ideas?


Solution

  • Hi this model wouldn't work fine.

    MVVMCViewController has hardcoded protocols as variable type, so You should have the same in your childVC.

    To make it work as u want MVVMCViewController show be generic (but can be a lot of issues with it), like

    class MVVMCViewController<T: Modelling, U: CoordinatorDelegate>: UIViewController {
        
        weak var coordinatorDelegate: U?
        var viewModel: T?
    
    }
    

    or add just casted properties to ConnectViewController

    class ConnectViewController: MVVMCViewController {
        
        weak var coordinatorDelegate: CoordinatorDelegate?
        var viewModel: Modelling?
        var currentDelegate: ConnectViewControllerCoordinatorDelegate? {
             coordinatorDelegate as? ConnectViewControllerCoordinatorDelegate
        }
        var currentVM: ConnectViewModel? {
             viewModel as? ConnectViewModel
        }
    }