1

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?

Xcoder
  • 1,433
  • 3
  • 17
  • 37
Pablo
  • 1,302
  • 1
  • 16
  • 35
  • just split it up and unwrap your optional index safely using `if let` or `guard let index = positiveEvents.index(where: { $0 === event }) else {` and get ride of the forced unwrapping – Leo Dabus Mar 11 '18 at 23:53
  • @LeoDabus Yeah, but it still seems a bit unreliable to keep my code that uses a closure and a === operator. Edit: seems to work fine though, could you please post that as an answer to finalize this inquiry – Pablo Mar 11 '18 at 23:55
  • 1
    if you would lite to use `index(of:)` with your custom type you need to make your type conform to `Equatable` protocol – Leo Dabus Mar 11 '18 at 23:59

1 Answers1

6

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!")
    }
  }
}
Dan Karbayev
  • 2,870
  • 2
  • 19
  • 28