Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.