How to pass a Swift Type into an Generic SwiftUI View?

Context

I am working with Generic SwiftUI Views and encountered a problem. I have a Generic SwiftUI View and when calling it, I need to specify the Type. However, I get this Type only as a return parameter from a method in an any format.

The following Code produces the following Compiler Error:

Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project

Cannot find type 'componentType' in scope


Code

protocol Component {
    var name: String { get }
}

struct GenericView<C: Component>: View {
    var component: C?

    var body: some View { Text(component.name) }
}

struct MainView: View {
    var body: some View {
        GenericView<componentType>()
    }

    private var componentType: any Component.Type {
        // This returns a specific Component Type, e.g. ComponentA.self
    }
}

Question

  • How can I achieve my goal of adjusting the Generic Type of GenericView depending on a Parameter / Method Return Value?

Could you not pass in the actual value to GenericView and remove the generics.

Something like this:

struct GenericView: View {
    var component: any Component

    var body: some View {
        Text(component.name)
    }
}

struct MainView: View {
    var body: some View {
        GenericView(component: componentType)
    }

    private var component: any Component {
        // This returns a value that conforms to Component
    }
}

Or would this not be possible because it removes the generics, or you just want the type being passed around instead of the actual value?


I don't know if any and generics work the best together. You could think of using some instead of any, but it's whatever suits your needs.

How to pass a Swift Type into an Generic SwiftUI View?
 
 
Q