I would like to pass an object that conforms to some protocol, and resolve its type for allocation with Swinject framwork (By dependency injection).
protocol IViewModelAware {
typealias T
var viewModel : T { get set }
}
class ViewAndViewModelCreator {
var container : Container
init(container : Container) {
self.container = container
}
func resolveViewModel<T : IViewModelAware>(controller : T) {
let mirror = Mirror(reflecting: controller.viewModel)
let viewModelClassType = mirror.subjectType
let viewModel = self.container.resolve(viewModelClassType.self) // This line shows error
controller.viewModel = viewModel
}
}
Error: Cannot invoke 'resolve' with an argument list of type '(Any.Type)'
How do I get the Class from an object that confirms to protocol, maybe there is another option except reflection?
You can get the type of the view model class from its instance by controller.viewModel.dynamicType
:
func resolveViewModel<T : IViewModelAware>(controller : T) {
let viewModel = container.resolve(controller.viewModel.dynamicType)
// ...
}