Skip to content

Instantly share code, notes, and snippets.

@MihailPreis
Created August 27, 2021 12:29
Show Gist options
  • Save MihailPreis/55ae7627193870caf59a2a5d9191779c to your computer and use it in GitHub Desktop.
Save MihailPreis/55ae7627193870caf59a2a5d9191779c to your computer and use it in GitHub Desktop.
Swift extension of Array for getting difference from two arrays.
extension Array where Element: Hashable {
/// Result entity for `diff(with:)`
typealias DiffResult = (old: [Element], changed: [Element], new: [Element])
/**
Return difference between two arrays.
- Parameter newArray: New array.
- Returns: DiffResult entity with:
- old items from current array,
- changed intersection items from new array
- new items from new array.
*/
func diff(with newArray: [Element]) -> DiffResult {
let itemsSet = Set(self)
let newItemsSet = Set(newArray)
return (
Array(itemsSet.subtracting(newItemsSet)),
Array(newItemsSet.intersection(itemsSet)),
Array(newItemsSet.subtracting(itemsSet))
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment