Skip to content

Instantly share code, notes, and snippets.

@florianpircher
Created April 2, 2017 16:22
Show Gist options
  • Save florianpircher/928062b345a5c84ed421dc6b39cc8ea2 to your computer and use it in GitHub Desktop.
Save florianpircher/928062b345a5c84ed421dc6b39cc8ea2 to your computer and use it in GitHub Desktop.
extension Sequence {
/**
Returns a filtered "view" of `self` where only one for all elements that return the same value for `taggingHandler` is kept. In other words: every element in the returned array was the first to return its value from `taggingHandler` when traversing the sequence in order.
```swift
[1, 1, 1, 2, 3, 3, 4, 5, 5, 5].unique { $0 }
// = [1, 2, 3, 4, 5]
[0, 1, -1, -2, 2, -3, -3].unique { abs($0) }
// = [0, 1, -2, -3]
```
- parameter taggingHandler: Returns a hashable value used to identify the unique values in the sequence.
*/
func unique<T: Hashable>(by taggingHandler: (_ element: Self.Iterator.Element) -> T) -> [Self.Iterator.Element] {
var knownTags = Set<T>()
return self.filter { element -> Bool in
let tag = taggingHandler(element)
if !knownTags.contains(tag) {
knownTags.insert(tag)
return true
}
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment