Home > Net >  How to use any Object and pass it into a Generic SwiftUI View?
How to use any Object and pass it into a Generic SwiftUI View?

Time:09-11

Context

I have a Protocol called Component and a Computed Variable, that returns a specific Object conforming to Component as any Component. I also have a Generic SwiftUI View accepting a Component.

Compiler Error: Type 'any Component' cannot conform to 'Component'


Code

protocol Component: ObservableObject { var name: String }

struct ComponentView<C: Component>: View {
    @ObservedObject var component: C

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

struct RootView: View {
    var body: some View {
        ComponentView(component: component) // Compiler Error
    }

    private var component: any Component { // Returns any Component }
}

Question

  • I understand that any Component and Component are two different Types. However, I am looking for a possibility to use the given Component in the ComponentView. How can I achieve this goal of using the returned Component inside ComponentView?

CodePudding user response:

The var component: any Component declaration means that the property can virtually hold any value that conforms to the protocol, meaning the exact type of the value stored there is to be determined at runtime.

On the other hand, ComponentView<C: Component> is a compile-time construct, and the compiler needs to know which type will fill in the blanks, something that is not possible due to the any construct.

You'll have to either

  • propagate any downstream - from RootView to ComponentView, and remove the generic on ComponentView, or
  • propagate the generic requirement upstream - from ComponentView to RootView, and make RootView generic.
  • Related