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
andComponent
are two differentTypes
. However, I am looking for a possibility to use the givenComponent
in theComponentView
. How can I achieve this goal of using the returnedComponent
insideComponentView
?
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 - fromRootView
toComponentView
, and remove the generic onComponentView
, or - propagate the generic requirement upstream - from
ComponentView
toRootView
, and makeRootView
generic.