inject viewmodel in uiviewcontroller using swinject in swift

To inject a ViewModel into a UIViewController using Swinject, follow the steps below:

  1. Create a Protocol for the ViewModel:
main.swift
protocol ViewModelProtocol {
    // Declare the required functions and variables here
}
88 chars
4 lines
  1. Create a Class for the ViewModel that confirms to the ViewModelProtocol:
main.swift
class ViewModel: ViewModelProtocol {
    // Implement the required functions and variables here
}
98 chars
4 lines
  1. Create a Swinject Container instance and configure it to inject the ViewModel
main.swift
let container = Container()

container.register(ViewModelProtocol.self) { _ in
    return ViewModel()
}
104 chars
6 lines
  1. In the UIViewController, create a private variable for the ViewModel and inject it using Swinject. This can be done using Constructor Injection:
main.swift
class ViewController: UIViewController {

    private let viewModel: ViewModelProtocol

    init(viewModel: ViewModelProtocol) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // The rest of your code here

}
358 chars
17 lines
  1. Resolve the ViewModel dependency and create an instance of the UIViewController using the init(viewModel:) initializer:
main.swift
let vc = ViewController(viewModel: container.resolve(ViewModelProtocol.self)!)
79 chars
2 lines

At this point, you have successfully injected the ViewModel into the UIViewController using Swinject.

gistlibby LogSnag