2

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:

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()])
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • This is because your `PageView` expects an array of views of a generic type `Page`. However, in your code you're passing two *different* types: View1 and View2. – pawello2222 Oct 08 '20 at 12:16
  • Btw this might help you: [How can I implement PageView in SwiftUI?](https://stackoverflow.com/questions/58388071/how-can-i-implement-pageview-in-swiftui) – pawello2222 Oct 08 '20 at 12:18
  • @pawello2222 Right, but how can I tell "Accept an array of objects, each implementing View"? – pistacchio Oct 08 '20 at 12:33
  • You can use `AnyView` like in the solution below. – pawello2222 Oct 08 '20 at 12:35
  • Also see: [How to have a dynamic List of Views using SwiftUI](https://stackoverflow.com/questions/56645647/how-to-have-a-dynamic-list-of-views-using-swiftui) – pawello2222 Oct 08 '20 at 13:19

1 Answers1

2

Here is possible solution

struct Reference: View {
    var body: some View {             
        PageView([AnyView(View1()), AnyView(View2())])
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690