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?

3
  • 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 Commented Mar 11, 2018 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 Commented Mar 11, 2018 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 Commented Mar 11, 2018 at 23:59

1 Answer 1

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!")
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.