How to pass generic views to a struct in SwiftUI (Failed to produce diagnostic for expression;)

I get the error Failed to produce diagnostic for expression; please file a bug report for the following code. It seems to me pretty straight forward, but probably it has something to do with generics. How to pass generic views to a struct?

In a SwiftUI view I have this:

Code Block swift
import SwiftUI
struct PageView<Page: View>: View {
var views: [UIHostingController<Page>]
init(_ views: [Page]) {
self.views = views.map { UIHostingController(rootView: $0) }
}
var body: some View {
Text("Page View")
}
}
struct View1: View {
var body: some View {
Text("View 1")
}
}
struct View2: View {
var body: some View {
Text("View 2")
}
}
struct Reference: View {
var body: some View { // <- Error here
PageView([View1(), View2()])
}
}


Thanks
Accepted Answer
When you use some generic type in your code, the generic parameter needs to be resolved to a specific type statically for each use.

If Page is resolved as View1, all the Page in PageView needs to be View1 and cannot be View2.

You may need to use type-erasure for your purpose.
Code Block
import SwiftUI
struct PageView: View {
var views: [UIHostingController<AnyView>]
init(_ views: [AnyView]) {
self.views = views.map { UIHostingController(rootView: $0) }
}
var body: some View {
Text("Page View")
}
}
struct View1: View {
var body: some View {
Text("View 1")
}
}
struct View2: View {
var body: some View {
Text("View 2")
}
}
struct Reference: View {
var body: some View {
PageView([AnyView(View1()), AnyView(View2())])
}
}


How to pass generic views to a struct in SwiftUI (Failed to produce diagnostic for expression;)
 
 
Q