Skip to content

Instantly share code, notes, and snippets.

@fdstevex
Created June 15, 2015 12:12
Show Gist options
  • Save fdstevex/b5784f55be4e71eb98f9 to your computer and use it in GitHub Desktop.
Save fdstevex/b5784f55be4e71eb98f9 to your computer and use it in GitHub Desktop.
Xcode Playground showing a Swift diffing algorithm suitable for performing delta updates to a WKInterfaceTable
// arr1 is the current list
// arr2 is the new list
// the insert and delete callbacks will be called - pass these
// through to WKInterfaceTable to perform a delta update
func diff<T: Comparable>(arr1: Array<T>, var arr2: Array<T>, insertFunc: (index: Int, item: T) -> Void, deleteFunc: (Int) -> Void) {
var idx1 = 0
var idx2 = 0
while (idx1 < arr1.count) {
// identical items; step to next one
if (idx2 < arr2.count && arr1[idx1] == arr2[idx2]) {
idx1++
idx2++
continue
}
// try to re-sync: scan ahead to see if there's a match
var matched = false
for (var findidx = idx2; findidx < arr2.count; findidx++) {
if (arr1[idx1] == arr2[findidx]) {
// Found it - delete everything between y and z
for (var delidx = idx2; delidx < findidx; delidx++) {
deleteFunc(idx2)
arr2.removeAtIndex(idx2)
}
matched = true
break;
}
}
if (matched) {
continue
}
// didn't find a[x] in b, so add it
insertFunc(index: idx2, item: arr1[idx1])
arr2.insert(arr1[idx1], atIndex: idx2)
idx1++
idx2++
}
// Remove items after the end
while (arr2.count > arr1.count) {
deleteFunc(idx1)
arr2.removeAtIndex(idx1)
}
}
let newArray = [ "Two", "Four", "Five" ]
let oldArray = [ "One", "Two", "Three", "Four" ]
var outArray = oldArray
diff(newArray, oldArray,
{ (index: Int, item: String) -> Void in
outArray.insert(item, atIndex: index)
},
{ (index: Int) -> Void in
outArray.removeAtIndex(index)
}
);
outArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment