Skip to content

Instantly share code, notes, and snippets.

@DineshKachhot
Created July 12, 2018 05:14
Show Gist options
  • Save DineshKachhot/ba82a4d1a10036d739ef725eea44ee2a to your computer and use it in GitHub Desktop.
Save DineshKachhot/ba82a4d1a10036d739ef725eea44ee2a to your computer and use it in GitHub Desktop.
Array extension to return the unique list of objects based on a given key.
extension Array {
func unique<T:Hashable>(by: ((Element) -> (T))) -> [Element] {
var set = Set<T>() //Keep unique list in a Set for fast retrieval
var orderedArray = [Element]() //Keeping the unique list of elements but ordered
for value in self {
if !set.contains(by(value)) {
set.insert(by(value))
orderedArray.append(value)
}
}
return orderedArray
}
}
@DineshKachhot
Copy link
Author

Usage Example...
let uniqueBasedOnName = results.unique{$0.name}

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