Created
September 25, 2018 12:53
-
-
Save mike-ferenduros/57d5167c5584afa4de412a6667450876 to your computer and use it in GitHub Desktop.
Update UICollectionView based on before and after arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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