Last active
March 23, 2017 15:34
-
-
Save christopherkriens/a30d89ebf91c93ce8bbce893d1284f85 to your computer and use it in GitHub Desktop.
Identify unique elements within a Swift Array, preserving original order
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
// Order does matter | |
extension Array where Element: Hashable { | |
var uniqueElements: [Element] { | |
var seen = Array<Element>() | |
var underlyingIterator = makeIterator() | |
while let next = underlyingIterator.next() { | |
if !seen.contains(next) { | |
seen.append(next) | |
} | |
} | |
return seen | |
} | |
} | |
// Usage: | |
[1,1,2,2,3,3].uniqueElements // Results in [1,2,3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment