Iterate over an array and delete events that is older than present's day.

Hi! I have an array with some parties information like date/place/day and time of the event in an array called events(eventos portuguese) and I want to iterate throught this array and check if the data of the event has passed today's date. This is the code I am using but for some reason that I don't know the forEach is not working:

 func checkEventsDate() {
        let dateFormatter = DateFormatter()
        
        self.eventos.forEach { item in
            guard let dt = dateFormatter.date(from: item.data) else { return }

            if dt > Date() {
                let index = self.eventos.firstIndex(of: item)
                self.eventos.remove(at: index!)
            } else {
                print("maior")
            }

        }
    }

what am I missing or what am I doing wrong? I dont get any error messages just the code doesnt work.

thank you very much

Modifying the number of elements in an array you are iterating over is problematic. I would suggest creating a copy of the array and iterate over that. You would want to delete items in the current array like you are now.

Hi @etavares , you don't necessarily need to copy the array if it is an @State variable. When do you iterate over this array? Is it on button press or when the view is shown (or some other time)?

I tested out your code with this, which did work and may help you with your own code.

import SwiftUI

struct ContentView: View {
    @State private var arr: [Date] = [.now, .distantPast, .distantFuture]
    var body: some View {
        VStack {
            List(arr, id: \.self) { item in
                Text(item.description)
            }
            Button("remove events") {
                checkEventsDate()
            }
            
        }
    }
    
    func checkEventsDate() {
           self.arr.forEach { item in
               if item > Date() {
                   let index = self.arr.firstIndex(of: item)
                   self.arr.remove(at: index!)
               } else {
                   print("maior")
               }
           }
       }
}
Iterate over an array and delete events that is older than present's day.
 
 
Q