pistacchio
pistacchio

Reputation: 58953

How to pass generic views to a struct in SwiftUI

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()])
    }
}

Upvotes: 2

Views: 1061

Answers (1)

Asperi
Asperi

Reputation: 258443

Here is possible solution

struct Reference: View {
    var body: some View {             
        PageView([AnyView(View1()), AnyView(View2())])
    }
}

Upvotes: 2

Related Questions