2

I'm trying to use a list of protocol that conforms to View with ForEach but it always complains about "Protocol can only be used as a generic constraint because it has Self or associated type requirements"

Here is what I've been trying with

protocol ItemView: View, Identifiable {
    associatedtype ContentView: View

    var title: String { get }
    var body: ContentView { get }
}

struct AItemView: ItemView {
    let id = UUID()
    var title: String
    var body: some View {
        Text("Item A \(title)")
    }
}

struct BItemView: ItemView {
    let id = UUID()
    var title: String
    var body: some View {
        Text("Item B \(title)")
    }
}

struct ListView: View {
    private var listItems: [ItemView] {
        return [AItemView(title: "A"), BItemView(title: "B")]
    }

    var body: some View {
        VStack {
            ForEach(listItems) { item in
                item
                Divider()
            }
        }
    }
}
3
  • Did you figure it out? Commented Feb 5, 2021 at 12:57
  • @michalmichalek unfortunately ... nope ... Commented Feb 8, 2021 at 0:26
  • Use instead approach like in stackoverflow.com/a/63611331/12299030 Commented Jul 3, 2022 at 12:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.