Hello,
I am building a SwiftUI macOS app that manipulates a set of views ("playgrounds"). Each playground has some specific info but all share a generic common View.
I also want an enum
to list all available views in my app.
I struggle with Swift existential types and protocol to model my data structures. In particular, I always end up with the error "Type any View can not conform to protocol View" Despite having read many docs and blog posts on existential types and why a protocol can not conform to itself. I am blocked on this.
Here is my code :
// the protocol all my playgrounds must implement
protocol PlaygroundComponent {
associatedtype Body: View
@ViewBuilder var component: Self.Body { get }
}
// a generic type that implements the common part of all the playgrounds + the specific part from subtypes
struct PlaygroundView<Content: PlaygroundComponent>: View {
let content : Content
var body: some View {
Text("reused content")
content.component
}
}
// a concrete playground, it defines only the specific part
struct ListModelsPlayground: PlaygroundComponent {
var component: some View {
Text("ListModelsPlayground")
}
}
// an enum that lists all the implementations I have (only one to keep this example short)
enum Playgrounds {
case listModels
var info: any PlaygroundView<PlaygroundComponent> { ListModelsPlayground() } // ---> compilation error : Type 'any PlaygroundComponent' cannot conform to 'PlaygroundComponent'
}
How can I model a generic view with individual subcomponents to later be part of such s
or List( ForEach { } )
SwiftUI views ?