Created
November 7, 2015 14:47
-
-
Save mihyaeru21/e1fff10bfd85398a6c60 to your computer and use it in GitHub Desktop.
make Array unique
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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