TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Remove item from an array if date is passed.

Forums > SwiftUI

Hi! I have an array of an object called EventInfo(date/name/place/price/info) and I want to remove an item from this array if today's date is passed the day of the event. I am using this code but it is not working:

    func checkEventsDate() {
        let dateFormatter = DateFormatter()

        self.eventosTrash.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!)
            }

        }

    }

thank u very much

3      

Use removeAll(where: )

eg

struct Event {
    var date: Date
    var name: String
    // etc
}

// MOCK DATA (do not use 86400 as day in production code)
var events = [
    Event(date: .now.addingTimeInterval(86400 * -5), name: "Event 5 days ago"),
    Event(date: .now.addingTimeInterval(86400 * -10), name: "Event 10 days ago"),
    Event(date: .now.addingTimeInterval(86400 * 5), name: "Event 5 days in future"),
    Event(date: .now.addingTimeInterval(86400 * 10), name: "Event 10 days in future")
]

func checkDateEvent() {
    events.removeAll(where: { $0.date < Date.now } )
}

checkDateEvent()

print(events) // prints [Event(date: 2023-12-06 12:12:09 +0000, name: "Event 5 days in future"), Event(date: 2023-12-11 12:12:09 +0000, name: "Event 10 days in future")]

While this will remove past events, this will lose the event (if that what you want ok), but you might be better to use a filter (events.filter { $0.date < Date.now }) to get future events but will still have the records for past events.

4      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.