SwiftUI - 列表给出错误 "Type of expression is ambiguous without more context"

SwiftUI - List gives error "Type of expression is ambiguous without more context"

我正在尝试实现一个多选列表。

这是代码:

import SwiftUI

struct MultiSelectionWithEditButton : View {
    var items = ["One","Two", "Three"]

    @State var selectedRows = Set<String>()

    var body: some View {
        NavigationView {
            List((items, id: \.self), selection: $selectedRows) { name in
                Text(name)
                    .font(.title)
                    .fontWeight(.bold)
                }
                .navigationBarItems(trailing: EditButton())
                .navigationBarTitle(Text("Selected \(selectedRows.count) rows"))
        }
    }
}

#if DEBUG
struct MultiSelectionWithEditButton_Previews : PreviewProvider {
    static var previews: some View {
        MultiSelectionWithEditButton()
    }
}
#endif

但我收到以下错误消息:

"Type of expression is ambiguous without more context"

如果有人能提供帮助,我们将不胜感激! :)

问题出在你的 Lists init.将其更改为 List,其中包含 ForEach,如下所示:

struct MultiSelectionWithEditButton : View {
    var items = ["One","Two", "Three"]

    @State var selectedRows = Set<String>()

    var body: some View {
        NavigationView {
            List(selection: $selectedRows){
                ForEach(items, id: \.self) { name in
                    Text(name)
                        .font(.title)
                        .fontWeight(.bold)
                }
            }
            .navigationBarItems(trailing: EditButton())
            .navigationBarTitle(Text("Selected \(selectedRows.count) rows"))
        }
    }
}