如何存储一个符合ListStyle协议的属性

How to store a property that conforms to the ListStyle protocol

目前我正在使用 .listStyle(InsetGroupedListStyle()) 修饰符设置 listStyle

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

我想在 ListView 中创建一个 属性 来存储 ListStyle。问题是 ListStyle 是一个协议,我得到:

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

我看了这个,但我不知道ListStyleassociatedtype是什么

您可以使用泛型让您的 listStyle 成为 一些 ListStyle 类型:

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