在我的多维列表中,尝试删除行时遇到问题-线程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
有关,在通过可观察对象更改重新加载视图时,import random
def lottery(ticket):
"""
Compare lottery ticket against lottery draws and print how many draws have taken place
to match the ticket.
"""
count = 0
run = True
while run:
lotto_num = [random.randint(1, 49) for _ in range(6)]
lotto_num[-1] = random.randint(1, 7)
if lotto_num != ticket:
print(f"No match! Your ticket {ticket}, Lottery ticket {lotto_num}")
count += 1
else:
print(f"Match! Your ticket {ticket} lottery ticket {lotto_num}")
print(f"{count} draws")
run = False
lottery([11, 12, 36, 39, 46, 1])
并没有减少。
答案 0 :(得分:1)
发生此问题是因为foreach循环中的范围是恒定的。必须将其更改为:
ForEach (appState.parents.indices, id: \.self) { parentIndex in