Home > Software design >  How to use the Generic Type of a Types Property?
How to use the Generic Type of a Types Property?

Time:10-18

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?

CodePudding user response:

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 {
        //...
        }
    }
}

CodePudding user response:

You should declare your componentVM like that:

@ObservedObject var componentVM: ComponentViewModel<SomeSolideType>

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

  • Related