Theo Kallioras
Theo Kallioras

Reputation: 3676

Remove / delete selected cells from UICollectionView causes index out of bounds [sometimes]

I have a comments array declared as: var comments: [String] which I populate it with some Strings and I also have a UICollectionView within which I present the comments. My code is the following when I try to delete the selected cells from the UICollectionView:

if let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems {

    for indexPath in indexPathsForSelectedItems {
        comments.remove(at: indexPath.item) //I have only one section
    }

    collectionView.deleteItems(at: indexPathsForSelectedItems)

}

The issue is that sometimes when I delete the selected items, it creates an out of bounds exception on the comments array.

However when I use the following approach (create a copy array and replace the original one with its copy) no problem occurs:

var indexes: [Int] = []
for indexPath in indexPathsForSelectedItems {
    indexes.append(indexPath.item)
}
var newComments: [String] = []
for (index, comment) in comments.enumerated() {
    if !indexes.contains(index) {
        newComments.append(comment)
    }
}
comments = newComments

Why is this happening?

I am using Swift 3 and XCode 8.2.1

Upvotes: 0

Views: 534

Answers (1)

Andreas
Andreas

Reputation: 2745

Sorting

If you're not sure that indexPathsForSelectedItems are sorted in descending order, and hence always deletes the highest index first, you will eventually run into an out of bounds. Deleting an item will change the indices for all array elements with higher indices.

You probably want to use indexPathsForSelectedItems.sorted(by: >).

Upvotes: 2

Related Questions