1

Currently I'm setting the listStyle with the .listStyle(InsetGroupedListStyle()) modifier.

struct ContentView: View {
    var body: some View {
        ListView()
    }
}

struct ListView: View {
    let data = ["One", "Two", "Three", "Four", "Five", "Six"]
    var body: some View {
        List {
            ForEach(data, id: \.self) { word in
                Text(word)
            }
        }
        .listStyle(InsetGroupedListStyle())
    }
}

I want to make a property inside ListView to store the ListStyle. The problem is that ListStyle is a protocol, and I get:

Protocol 'ListStyle' can only be used as a generic constraint because it has Self or associated type requirements

struct ContentView: View {
    var body: some View {
        ListView(listStyle: InsetGroupedListStyle())
    }
}

struct ListView: View {
    var listStyle: ListStyle /// this does not work
    let data = ["One", "Two", "Three", "Four", "Five", "Six"]
    var body: some View {
        List {
            ForEach(data, id: \.self) { word in
                Text(word)
            }
        }
        .listStyle(listStyle)
    }
}

I looked at this question, but I don't know what ListStyle's associatedtype is.

aheze
  • 24,434
  • 8
  • 68
  • 125

1 Answers1

2

You can use generics to make your listStyle be of some ListStyle type:

struct ListView<S>: View where S: ListStyle {
    var listStyle: S
    let data = ["One", "Two", "Three", "Four", "Five", "Six"]
    var body: some View {
        List {
            ForEach(data, id: \.self) { word in
                Text(word)
            }
        }
        .listStyle(listStyle)
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209