Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaeleisel/0f19b0a2d1fbe2a71b039b9e508fa163 to your computer and use it in GitHub Desktop.
Save michaeleisel/0f19b0a2d1fbe2a71b039b9e508fa163 to your computer and use it in GitHub Desktop.
extension Array where Element: Hashable {
func uniqueElements() -> [Element] {
return uniqueElements(by: { $0 })
}
func uniqueElements<T: Hashable>(by uniqueValue: (Element) -> T) -> [Element] {
var uniqueElements: [Array.Element] = []
var set: Set<T> = Set()
for element in self {
let value = uniqueValue(element)
if set.contains(value) {
continue
}
set.insert(value)
uniqueElements.append(element)
}
return uniqueElements
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment