Context
I have a SwiftUI
View
which gets initialised with a ViewModel
(Observable Object
). This ViewModel
itself has a Generic Type
.
I am now trying to use the Generic Type
of the ViewModel
inside the View
itself, however, can’t get hold of it.
Code
class ComponentViewModel<C: Component>: ObservableObject { ... }
struct SomeView: View {
@ObservedObject var componentVM: ComponentViewModel
init(with componentVM: ComponentViewModel) {
componentVM = componentVM
}
var body: some View {
switch componentVM.C.self { ... } // This does not work.
}
Question
- How can I use the
Generic Type
ofTypes Property
, in this case ofcomponentVM
?
2
Answers
You should declare your componentVM like that:
SomeSolidType should be some class / struct conforming to your Component protocol.
You need to make your View generic as well
and then you use
ModelType
in your code to refer to the generic type of the view model