inject viewmodel in uiviewcontroller in swift

To inject a ViewModel into a UIViewController, you can use Dependency Injection. Here is an example of how to do it in Swift:

  1. Define your ViewModel protocol:
main.swift
protocol MyViewModelProtocol {
    // Define your ViewModel methods and properties here
}

91 chars
5 lines
  1. Create your ViewModel class which implements the ViewModel protocol:
main.swift
class MyViewModel: MyViewModelProtocol {
    // Implement your ViewModel methods and properties here
}
103 chars
4 lines
  1. In your UIViewController, add a property to hold the ViewModel:
main.swift
class MyViewController: UIViewController {

    var viewModel: MyViewModelProtocol!
    
    // ...
}
102 chars
7 lines
  1. Instantiate your ViewModel using Dependency Injection when creating your UIViewController, for example in a factory method:
main.swift
func createMyViewController() -> UIViewController {
    let viewController = MyViewController()
    let viewModel = MyViewModel()
    viewController.viewModel = viewModel
    return viewController
}
199 chars
7 lines

Now your UIViewController has access to the methods and properties of the ViewModel through the viewModel property. You can use this to update the UI based on changes in the ViewModel, or to trigger actions on the ViewModel based on user interaction.

gistlibby LogSnag