Pablo
Pablo

Reputation: 1332

Removing a specific object from an array in Swift 4

I am trying to remove a specific Event object (my own class) from an array hold Event objects. This is my declaration of the array.

private var positiveEvents : [Event] = []

Now, here is what how I am trying to remove the Event object from the array. This method (disposeOfflineEvents) is called every 30 seconds, so positiveEvents might have some elements or none at all.

func disposeOfflineEvents() {
    for event in positiveEvents {
        if !event.ongoing {
            positiveEvents.remove(at:  positiveEvents.index(where: { $0 === event })!)
            print("! - Disposing of an event!")
        }
    }
}

I saw this question, but I am using Swift 4, so I don't have the index(of: Event) method. The problem with my current solution is that I occasionally get an error when using "===" for checking equality of objects:

enter image description here

Is there any better way of doing this?

Upvotes: 1

Views: 5689

Answers (1)

Dan Karbayev
Dan Karbayev

Reputation: 2920

You should avoid force unwrapping in general, and your case in particular because chances are high that the array won't have an element that satisfies the condition. Instead, you can use optional binding (note that you can combine for loop with where):

func disposeOfflineEvents() {
  for event in positiveEvents where !event.ongoing {
    if let index = positiveEvents.index(where: { $0 === event }) {
      positiveEvents.remove(at: index)
      print("! - Disposing of an event!")
    }
  }
}

Upvotes: 6

Related Questions