Super easy to reproduce.
Swiping to delete on the last remaining item in the list causes an index out of bounds exception. If you have 2 items in your list, it will only happen when you delete the last remaining item.
From my testing, this issue occurs on 18.3.1 and onward (the RC it happens). I didn't test 18.3.0 so it might happen there as well.
The only workarounds I have found is to add a delay before calling my delete function:
OR
to comment out the Toggle.
So it seems as though iOS 18.3.x added a race condition in the way the ForEach accesses the values in its binding.
Another thing to note, this also happens with .swipeActions, EditMode, etc... any of the built in ways to delete an item from a list.
import SwiftUI
struct ContentView: View {
@StateObject var viewModel = ContentViewModel()
var body: some View {
List {
ForEach($viewModel.items) { $item in
HStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text($item.text.wrappedValue)
Spacer()
Toggle(String(""), isOn: $item.isActive)
.labelsHidden()
}
}
.onDelete(perform: delete)
}
}
func delete(at offsets: IndexSet) {
// uncomment task to make code not crash
// Task {
viewModel.deleteItem(at: offsets)
// }
}
}
struct MyItem: Identifiable {
var id: UUID = UUID()
var text: String
var isActive: Bool
}
class ContentViewModel: ObservableObject {
@Published var items: [MyItem] = [MyItem(text: "Hello, world!", isActive: false)]
func deleteItem(at offset: IndexSet) {
items.remove(atOffsets: offset)
}
}