0

I'm adding values to an array when a user clicks a cell like so:

var savedArray = [] as Array
self.savedArray.append(obj[indexPath.row].title as Any)

This is successfully saving the values. But, when I want to remove them (when they deselect the cell) it says 'Fatal Index out of range'.

let number = indexPath.row       
self.savedArray.remove(at: number)

Oddly enough, this code works for the first (0) indexPath, but not the others. Is there a fix? Thank you.

5
  • 1
    The value of number variable is verly likely going beyond the borders of your array... Have you tried printing it ? Commented Aug 2, 2020 at 19:58
  • 1
    You are using an index of a different collection. Why would you expect both elements to be in the same index? Commented Aug 2, 2020 at 20:05
  • First change the declaration of your savedArray. Don't use Any. Use the type of your element. Make your Element (probably a String) and conform to Equatable (if it doesn't String does conform to Equatable). Then find the firstIndex of your element in your savedArray and remove it. Commented Aug 2, 2020 at 20:08
  • @cocool97 Yes, when I print it it does successfully show the IndexPath. Commented Aug 2, 2020 at 20:17
  • @LeoDabus if I do that it just says Protocol 'Equatable' can only be used as a generic constraint because it has Self or associated type requirements Commented Aug 2, 2020 at 20:19

1 Answer 1

1

You are using an index of a different collection. Why would you expect both elements to be in the same index? What happens is that the two collection have different number of elements. First change the declaration of your savedArray. Don't use Any. Use the type of your element. Make your array type the same type as your title property. Then find the firstIndex of your element in your savedArray and remove it.

Your code should look something like this (if your title property is a String):

Array declaration:

var savedArray: [String] = []

Appending new elements:

self.savedArray.append(obj[indexPath.row].title)

Removing the element:

if let index = self.savedArray.firstIndex(of: obj[indexPath.row].title) {
    self.savedArray.remove(at: index)
}      
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.