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()])
    }
}
5
  • 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. Commented Oct 8, 2020 at 12:16
  • Btw this might help you: How can I implement PageView in SwiftUI? Commented Oct 8, 2020 at 12:18
  • @pawello2222 Right, but how can I tell "Accept an array of objects, each implementing View"? Commented Oct 8, 2020 at 12:33
  • You can use AnyView like in the solution below. Commented Oct 8, 2020 at 12:35
  • Also see: How to have a dynamic List of Views using SwiftUI Commented Oct 8, 2020 at 13:19

1 Answer 1

2

Here is possible solution

struct Reference: View {
    var body: some View {             
        PageView([AnyView(View1()), AnyView(View2())])
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.