Skip to content

Instantly share code, notes, and snippets.

@christopherkriens
Last active March 23, 2017 15:34
Show Gist options
  • Save christopherkriens/a30d89ebf91c93ce8bbce893d1284f85 to your computer and use it in GitHub Desktop.
Save christopherkriens/a30d89ebf91c93ce8bbce893d1284f85 to your computer and use it in GitHub Desktop.
Identify unique elements within a Swift Array, preserving original order
// 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