ForEach - Deleting last index causes Index out of bounds error

Hello everyone,

I trying to draw a custom view inside a for each (list style), that is inside a Scroll View, that is inside a Navigation view. Like this.

Navigation View {
    ScrollView {
         ForEach(array of objects ...) {
               CustomView()
         }
    }
}

The custom view calls up a sheet that has a button that is able to delete elements inside the collection used in the foreach.

Unless I use this asyncAfter after dismissing the sheet I always get index out of bounds when I try to remove the last element of the array of objects in the for each:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            workouts.removeAll(where: { $0.id == workoutToRemoveID })
        }

I have been trying to solve this bug, but so far no luck. Could you give me a hand?

Thank you for your help!

Please show the complete code for

         ForEach(array of objects ...) {

Do you define the id ?

ForEach(arrayOfObjects, id: \.self )

Can you show a complete code? (It can be simplified, but ready to run.)

Here is my code:

Here is my code:

@Binding var workouts: [Workout]
@State private var showWorkoutStudioEditor = false
@State private var sortedBy: SortBy = .nameAscending

    
@Environment(\.scenePhase) private var scenePhase

let saveAction: () -> Void

var body: some View {

        NavigationView {

            ScrollView(showsIndicators: true) {

                ForEach($workouts, id: \.id) { workout in

                    if !(sortedBy == .favorites) || workout.isFavorite.wrappedValue {

                        WorkoutCard(

                            workout: workout,

                            workouts: $workouts,

                            removeWorkout: removeWorkout

                        )
                            .padding([.leading, .trailing])
                    }
                }
         }
}

ForEach - Deleting last index causes Index out of bounds error
 
 
Q