Reputation: 1703
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
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
?Upvotes: 0
Views: 871
Reputation: 32904
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
any
downstream - from RootView
to ComponentView
, and remove the generic on ComponentView
, orComponentView
to RootView
, and make RootView
generic.Upvotes: 1