With the intention to obtain this, we have to maintain observe of each the outdated information supply and its index paths, in addition to the brand new information supply and its index paths. Notice that the index paths of the operations should not overlap with one another.
Say the unique information supply is [1, 2, 3, 4, 5]
The brand new information comes as [3, 2, 6, 7].
We need to take away [4, 5], put new information in entrance, then append remainder of the outdated information.
So the brand new information supply is [3, 2, 6, 7, 1]
@objc func performBatchUpdates() {
// Assemble new information supply
let newData = serviceData[1].map { PostCell.Mannequin(num: $0)}
var tmpDataSource = dataSource
tmpDataSource.removeLast()
tmpDataSource.removeLast()
let newOrder = newData + tmpDataSource.filter { !newData.comprises($0) }
// Calculate take away indexes relative to outdated indexes.
// Calculate insert indexes relative to new indexes.
// Calculate transfer indexes relative to each.
var deleteIndexes = [IndexPath]()
var insertIndexes = [IndexPath]()
var strikes = [(from: IndexPath, to: IndexPath)]()
var oldPostToIndex = [PostCellModel: Int]()
for (i, put up) in dataSource.enumerated() {
oldPostToIndex[post] = i
}
var newPostToIndex = [PostCellModel: Int]()
for (i, put up) in newOrder.enumerated() {
newPostToIndex[post] = i
}
for (put up, i) in oldPostToIndex {
if newPostToIndex[post] == nil {
deleteIndexes.append(IndexPath(row: i, part: 0))
}
}
for (put up, newIndex) in newPostToIndex {
if let oldIndex = oldPostToIndex[post] {
if oldIndex != newIndex {
strikes.append((from: IndexPath(row: oldIndex, part: 0), to: IndexPath(row: newIndex, part: 0)))
}
} else {
insertIndexes.append(IndexPath(row: newIndex, part: 0))
}
}
// Replace the ultimate dataSource
dataSource = newOrder
// Step 3: Carry out batch updates
tableView.performBatchUpdates {
tableView.deleteRows(at: deleteIndexes, with: .computerized)
tableView.insertRows(at: insertIndexes, with: .computerized)
for transfer in strikes {
tableView.moveRow(at: transfer.from, to: transfer.to)
}
}