如何在SwiftUI中手动从列表中删除项目?

如何在SwiftUI中手动从列表中删除项目?,swiftui,Swiftui,我试图从列表中删除某些项,但得到一个错误线程1:致命错误:索引超出范围。我知道onDelete,但在macOS上不清楚如何用鼠标调用它 @State var wishList=[ “项目1”, “项目2” ] 名单{ ForEach(wishList.index){index in 按钮(操作:{ }) { HStack{ Text(self.wishList[index])//线程1:致命错误:索引超出范围。 按钮(操作:{ RunLoop.main.perform{ self.wishLis

我试图从列表中删除某些项,但得到一个错误
线程1:致命错误:索引超出范围
。我知道onDelete,但在macOS上不清楚如何用鼠标调用它

@State var wishList=[
“项目1”,
“项目2”
]
名单{
ForEach(wishList.index){index in
按钮(操作:{
}) {
HStack{
Text(self.wishList[index])//线程1:致命错误:索引超出范围。
按钮(操作:{
RunLoop.main.perform{
self.wishList.remove(at:index)
}
}) {
图像(系统名称:“减号.circle”).foregroundColor(.red)
}
}
}
}
}
修复: 我添加了
id:\.self
来修复我的代码

@State var wishList=[
“项目1”,
“项目2”
]
名单{
ForEach(wishList.index,id:\.self){中的索引
按钮(操作:{
}) {
HStack{
Text(self.wishList[index])//线程1:致命错误:索引超出范围。
按钮(操作:{
RunLoop.main.perform{
self.wishList.remove(at:index)
}
}) {
图像(系统名称:“减号.circle”).foregroundColor(.red)
}
}
}
}
}

错误中给出了原因:

计数(1)!=其初始计数(2)
ForEach(uquo:content:)
只能用于常量数据。相反,将数据与可识别的一致,或者使用ForEach(uu:id:content:)并提供明确的
id

相反,请使用可识别的版本,并直接对内容进行操作:

    List {
        ForEach(wishList, id: \.self) { content in
            HStack {
                Text(verbatim: content)

                Button(action: {
                    guard let index = self.wishList.firstIndex(of: content) else { return }
                    self.wishList.remove(at: index)
                }) {
                    Image(systemName: "minus.circle").foregroundColor(.red)
                }
            }
        }
    }
编辑:这里有一个更简单的版本:

    List(0..<wishList.count, id: \.self) { index in
        HStack {
            Text(verbatim: self.wishList[index])

            Button(action: {
                self.wishList.remove(at: index)
            }) {
                Image(systemName: "minus.circle").foregroundColor(.red)
            }
        }
    }

List(0..谢谢,要修复我的代码,我需要将
id:\.self
添加到
ForEach
中。我在帖子中添加了修复代码。谢谢,您的帖子帮助我找到了正确的解决方案。