我有一个可观察的对象,这是我独特的事实来源:
class NetworkFetcher: ObservableObject {
@Published var list: [Car] = [Car(id: UUID().uuidString, name: "Tesla"), Car(id: UUID().uuidString, name: "BMW")]
func erase() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
self.list = []
}
}
func add() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
self.list = [Car(id: UUID().uuidString, name: "Tesla S"), Car(id: UUID().uuidString, name: "BMW M3")]
}
}
}
这是车:
struct Car: Identifiable, Hashable {
var id: String
var name: String
}
这里擦除和添加(编辑列表的功能)工作,一切正常:
struct ContentView: View {
@ObservedObject var net: NetworkFetcher = NetworkFetcher()
var body: some View {
NavigationView {
VStack {
ListView(liste: self.$net.list, net: self.net)
Button(action: {
self.net.erase()
}) {
Text("erase")
}
Button(action: {
self.net.add()
}) {
Text("add")
}
}
}
}
}
struct ListView: View {
@Binding var liste: [Car]
@ObservedObject var net: NetworkFetcher
var body: some View {
List {
ForEach(liste.indices, id: \.self) { i in
NavigationLink(destination: CarView(c: self.$liste[i], net: self.net)) {
Text(self.liste[i].name)
}
}
}
}
}
问题在这里:
struct CarView: View {
@Binding var c: Car
@ObservedObject var net: NetworkFetcher
var body: some View {
VStack {
TextField("car name :", text: $c.name)
Button(action: {
self.net.erase()
}) {
Text("erase")
}
Button(action: {
self.net.add()
}) {
Text("add")
}
}
}
}
如果我单击擦除按钮,主列表将变为一个空数组。但是应用程序崩溃了,我收到了这个错误:
致命错误:索引超出范围:文件 /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,第 444 行
问题是 :
- 为什么 ?
- 如何解决?
此致