1

在我的多维列表中,当我尝试删除行时遇到问题 - 线程 1:致命错误:索引超出范围:

struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar")]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            List {
                ForEach (0..<appState.parents.count) { parentIndex in
                    NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                        Text(self.appState.parents[parentIndex].name) // Thread 1: Fatal error: Index out of range
                    }
                }
                .onDelete(perform: deleteItem)
            }
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        List {
            ForEach (0..<(appState.parents[parentIndex].children?.count ?? 0)) { childIndex in
                Text(self.appState.parents[self.parentIndex].children![childIndex].name)
            }
        }
    }
}

我重建了这种情况,因为我在一个具有更多代码的更大项目中遇到了这个问题。尤其是当我尝试删除有孩子的父母时,我在儿童视图中遇到了问题。对于没有孩子的父母,我可以删除它们。在这段代码中,我根本无法删除一行。

我认为这个问题在某种程度上与parentIndex视图通过可观察对象更改重新加载时没有减少有关。

4

1 回答 1

1

出现此问题的原因是 foreach 循环中的范围是恒定的。必须改为:

ForEach (appState.parents.indices, id: \.self) { parentIndex in

于 2020-06-01T10:27:49.637 回答