skip to Main Content

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 of Types Property, in this case of componentVM?

2

Answers


  1. You should declare your componentVM like that:

    @ObservedObject var componentVM: ComponentViewModel<SomeSolideType>
    

    SomeSolidType should be some class / struct conforming to your Component protocol.

    Login or Signup to reply.
  2. You need to make your View generic as well

    struct SomeView<ModelType: Component>: View
    

    and then you use ModelType in your code to refer to the generic type of the view model

    struct SomeView<ModelType: Component>: View {
        @ObservedObject var componentVM: ComponentViewModel<ModelType>
    
        init(with componentVM: ComponentViewModel<ModelType>) {
            self.componentVM = componentVM
        }
    
        var body: some View {
            switch ModelType.self {
            //...
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search