0

I'm having trouble with Swift arrays. I want to add and remove items from an array in a single transaction when I have the indexes of items to add or remove.

array.insert(insertions.map({return (viewModels[$0], NSIndexPath(forRow: $0, inSection: 0))}))
array.remove(deletions.map{NSIndexPath(forRow: $0, inSection: 0)})

However when I remove the indexes, it breaks the order for adding items and adds them in the wrong position.

The idea would be something like:

array.update({
   array.insert(insertions.map({return (viewModels[$0], NSIndexPath(forRow: $0, inSection: 0))}))
   array.remove(deletions.map{NSIndexPath(forRow: $0, inSection: 0)})
})

Then combine them somehow, ideally I'd like to have multiple addition and removal capabilities.

Aaron
  • 6,466
  • 7
  • 37
  • 75
Andrius Steponavičius
  • 8,074
  • 3
  • 22
  • 25
  • I am not familiar with such functionality. This is what `UITableView` does internally, for example. Not sure if this should be a core framework functionality; if you believe it should be, consider opening an enhancement request at https://bugs.swift.org/. – Léo Natan Oct 20 '16 at 17:19
  • If possible, I would try and make the items of the array Equatable and deal with index(of:) rather than keeping track of indexes in a changing array. Another option would be to make them Hashable/Comparable and use Sets and sort(), which are much better set up to deal with this kind of thing without having to micro manage it at the point of use. – GetSwifty Oct 20 '16 at 19:46

0 Answers0