I have a simple list populated using a view-model:
@ObservedObject var sdvm = StepDataViewModel()
[...]
List {
ForEach (vm.steps.indices, id: \.self) { idx in
TheSlider(value: self.$vm.steps[idx].theValue, index: self.vm.steps[idx].theIndex)
}
.onDelete(perform: { indexSet in
self.vm.removeStep(index: indexSet) // <--- here
})
}
Where the viewmodel is this:
class StepDataViewModel: ObservableObject {
@Published var steps: [StepData] = []
func removeStep(index: IndexSet) {
steps.remove(atOffsets: index)
}
}
and the StepData is this one:
struct StepData: Equatable, Hashable {
var theIndex: Int
var theValue: Double
}
TheSlider:
struct TheSlider: View {
@Binding var value: Double
@State var index: Int
var body: some View {
ZStack {
Slider(value: $value, in: 0...180, step: 1)
.padding()
HStack {
Text("[\(index)]")
.font(.body)
.fontWeight(.black)
.offset(y: -20.0)
Text("\(Int(value))")
.offset(y: -20.0)
}
}
}
}
Now, .onDelete
is obviously attached to the List, so I receive the correct row index
when press delete.
For what reason the app crash for index-out-of-bound? Is the list that pass me the index, or not?
I receive this error:
Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
Can be caused by the direct array reference in the "TheSlider
"? If yes, how I can change it using theValue
as Binding
updatable?