Skip to content

Instantly share code, notes, and snippets.

@albertbori
Last active August 9, 2018 10:13
Show Gist options
  • Save albertbori/0b26c8190ab0469e49d7e4714f18ffe9 to your computer and use it in GitHub Desktop.
Save albertbori/0b26c8190ab0469e49d7e4714f18ffe9 to your computer and use it in GitHub Desktop.
An extension for Swift Array that returns the difference between two arrays
//: Playground - noun: a place where people can play
extension Array where Element: Comparable {
/**
Compares array with passed array and returns the differences. Warning: Must be a set of data (no duplicate values)
- Parameter with: The new array to compare to the existing array
- Returns: A tuple with an array of added items and an array of removed items.
*/
func diff(with array: Array) -> (added: Array, removed: Array) {
let originalArray = self.sorted()
let newArray = array.sorted()
var addedItems: [Element] = []
var removedItems: [Element] = []
var originalIndex = 0
var newIndex = 0
while originalIndex < originalArray.count && newIndex < newArray.count {
if originalArray[originalIndex] < newArray[newIndex] {
removedItems.append(originalArray[originalIndex])
originalIndex += 1
} else if originalArray[originalIndex] > newArray[newIndex] {
addedItems.append(newArray[newIndex])
newIndex += 1
} else {
newIndex += 1
originalIndex += 1
}
}
if newIndex < newArray.count {
addedItems.append(contentsOf: newArray[newIndex..<newArray.count])
}
if originalIndex < originalArray.count {
removedItems.append(contentsOf: originalArray[originalIndex..<originalArray.count])
}
return (added: addedItems, removed: removedItems)
}
}
let original = [7, 3, 4, 6]
let new = [2, 4, 9, 10, 7]
let result = original.diff(with: new)
print(result.added) //prints [2, 9, 10]
print(result.removed) //prints [3, 6]
@albertbori
Copy link
Author

albertbori commented Jul 31, 2018

Or just use set:

let original = Set([7, 3, 4, 6, 7])
let new = Set([2, 4, 9, 10, 7])

let removed = original.subtracting(new)
let added = new.subtracting(original)

print(removed) //prints [6, 3]
print(added) //prints [10, 2, 9]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment