Created
March 12, 2019 20:41
-
-
Save michaeleisel/0f19b0a2d1fbe2a71b039b9e508fa163 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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