当我尝试使用导航删除列表视图中的一行时超出索引 link

out of index when i try to remove one row in a listview with navigation link

    struct PocketListView: View {
    @EnvironmentObject var pocket:Pocket
    var body: some View {
        NavigationView{
            List{
                ForEach(self.pocket.moneyList.indices,id: \.self){index in
                    NavigationLink(destination:  MoneyView(money: self.$pocket.moneyList[index])){
                        MoneyNoTouchView(money: self.$pocket.moneyList[index])
                    }


                }.onDelete(perform: {index in
                    self.pocket.moneyList.remove(at: index.first!)
                })
                Spacer()
                HStack{
                    Image(systemName: "plus")
                        .onTapGesture {
                            self.pocket.add()
                    }
                }

            }
        }

    }
}


    struct Money {
    var id = UUID()
    var value = 0
}

    class Pocket: ObservableObject,Identifiable {
        @Published var id = UUID()
        @Published var moneyList = [Money]()

        func add() {
            self.moneyList.append(Money())
            print(moneyList.count)
        }
    }

当我尝试删除任何行时,应用程序会崩溃,我得到这个"Fatal error: Index out of range"。 如果我删除代码中的 NavigationLink 部分,则可以删除任何行。 我该如何解决这个问题? 谢谢。

谢谢你的代码。

我不得不 change/extend 一些事情,因为仍然缺少一些代码来编译您的示例,但我的代码有效....也许它可以帮助您

import SwiftUI


struct A : View {

    var body: some View {
        Text("a")
    }
}

struct ContentView: View {
    @EnvironmentObject var pocket:Pocket
    var body: some View {
        NavigationView{
            List{
                ForEach(self.pocket.moneyList.indices,id: \.self) { index in
                    NavigationLink(destination: A()){
                        Text("\(self.pocket.moneyList[index].value)")
                    }


                }.onDelete(perform: {index in
                    self.pocket.moneyList.remove(at: index.first!)
                })
                Spacer()
                HStack{
                    Image(systemName: "plus")
                        .onTapGesture {
                            self.pocket.add()
                    }
                }
            }
        }
    }
}


struct Money {
    var id = UUID()
    var value = 0
}

class Pocket: ObservableObject,Identifiable {
    @Published var id = UUID()
    @Published var moneyList = [Money]()

    func add() {
        self.moneyList.append(Money())
        print(moneyList.count)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

        var pocket = Pocket()
        pocket.moneyList.append(Money(id: UUID(), value: 1))
        pocket.moneyList.append(Money(id: UUID(), value: 2))
        pocket.moneyList.append(Money(id: UUID(), value: 3))

        return ContentView().environmentObject(Pocket())
    }
}