我有以下代码,尝试删除该行时崩溃。
Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
2020-10-02 17:08:37.983723-0400 HapticFactory[4201:213536] Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
该如何解决?还是我必须以其他方式解决这个问题?
代码:
import SwiftUI
struct Tag: Identifiable {
var id = UUID()
var value: String = "ColorBlue"
var color: Color = .blue
}
class ItemsViewModel: ObservableObject {
@Published var tags: [Tag] = []
func addTag(tag: Tag) {
tags.append(tag)
}
}
struct ContentView: View {
@ObservedObject var viewModel = ItemsViewModel()
var body: some View {
List {
ForEach(self.viewModel.tags.indices, id: \.self) { index in
ColorPicker(selection: self.$viewModel.tags[index].color) {
TextField("", text: self.$viewModel.tags[index].value)
}
}.onDelete(perform: self.deleteRow)
Button(action: { self.viewModel.addTag(tag: Tag()) }, label: {
Text("Add Tag")
})
}
}
private func deleteRow(at indexSet: IndexSet) {
self.viewModel.tags.remove(atOffsets: indexSet)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}