Skip to content

Instantly share code, notes, and snippets.

@mihyaeru21
Created November 7, 2015 14:47
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 mihyaeru21/e1fff10bfd85398a6c60 to your computer and use it in GitHub Desktop.
Save mihyaeru21/e1fff10bfd85398a6c60 to your computer and use it in GitHub Desktop.
make Array unique
extension Array {
func uniqBy<KeyType: Hashable>(@noescape hash: (Element) -> KeyType) -> [Element] {
var seen: [KeyType: Bool] = [:]
return self.filter { element in
let key = hash(element)
if seen[key] == nil {
seen[key] = true
return true
}
return false
}
}
mutating func uniqInPlaceBy<KeyType: Hashable>(@noescape hash: (Element) -> KeyType) {
self = self.uniqBy(hash)
}
}
extension Array where Element: Hashable {
func uniq() -> [Element] {
return self.uniqBy { $0 }
}
mutating func uniqInPlace() {
self = self.uniq()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment