Skip to content

Instantly share code, notes, and snippets.

@mike-ferenduros
Created September 25, 2018 12:53
Show Gist options
  • Save mike-ferenduros/57d5167c5584afa4de412a6667450876 to your computer and use it in GitHub Desktop.
Save mike-ferenduros/57d5167c5584afa4de412a6667450876 to your computer and use it in GitHub Desktop.
Update UICollectionView based on before and after arrays
extension UICollectionView {
///Perform batch update based on before and after arrays
///An array must not contain duplicate values
func batchUpdate<T: Equatable>(section: Int, from oldData: [T], to newData: [T], completion: ((Bool) -> Void)? = nil) {
performBatchUpdates({
let deletions = oldData.indices.filter { !newData.contains(oldData[$0]) }
deleteItems(at: deletions.map { IndexPath(item: $0, section: section) })
let insertions = newData.indices.filter { !oldData.contains(newData[$0]) }
insertItems(at: insertions.map { IndexPath(item: $0, section: section) })
for (oldIndex, value) in oldData.enumerated() {
if let newIndex = newData.firstIndex(of: value) {
assert(newIndex == newData.lastIndex(of: value))
moveItem(at: IndexPath(item: oldIndex, section: section), to: IndexPath(item: newIndex, section: section))
}
}
}, completion: completion)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment