Home > Enterprise >  How can I force to set type viewmodel in every viewcontroller on swift
How can I force to set type viewmodel in every viewcontroller on swift

Time:07-29

I'm stuck in the problem.

I am making project with MVVM, and I'm going to make all viewcontrollers have to set their own type of viewmodel class every being created.

But it is quite hard to make it as I thought.

Can I get any solution from you guys. Thanks

extension BaseViewController {
    class func openViewController(storyBoard: StoryBoardName = .main, viewModel: BaseViewModel, animated: Bool) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let nav = appDelegate.navigationController else { return }
        guard let vc = self.getViewController(storyBoard: storyBoard) else { return } // it is custom class to get viewcontroller from storyboard.
        **vc.viewModel = viewModel** // How can I use this code. Every ViewControllers have their own type of viewModel are inherited BaseViewModel class.
        DispatchQueue.main.async {
            nav.pushViewController(vc, animated: animated)
        }
    }
}

-----------edit---------------

BaseViewController : Parent Viewcontroller class of all viewcontrollers, and has generic viewmodel property to make child define and set type of it when open child with extension. <- That is problem I'm stuck. I wanna implement that opening child viewcontrollers in BaseViewController's extension.

BaseViewModel : Parent ViewModel class. And All child viewcontrollers have their own viemodel with own type what is inherited BaseViewModel class. So if opening child viewcontrollers, developers have to set type of ViewModel before opening.

CodePudding user response:

You are looking to implement generics.

See basic example below

class ViewController<T: SomeProtocolOrBaseClass> {
    // Overridables
}

class SomeViewController: ViewController<SomeProtocolOrBaseClass> {

}
  • Related