Skip to content

Instantly share code, notes, and snippets.

@johnkodes
Created March 7, 2023 13:25
Show Gist options
  • Save johnkodes/826be0b197b7462d46feed4d5d49ebb1 to your computer and use it in GitHub Desktop.
Save johnkodes/826be0b197b7462d46feed4d5d49ebb1 to your computer and use it in GitHub Desktop.
Unique elements from Sequence
extension Sequence {
/// Returns an array containing, in order, the first instances of
/// elements of the sequence that compare equally for the keyPath.
func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> [Element] {
var unique = Set<T>()
return filter { unique.insert($0[keyPath: keyPath]).inserted }
}
}
extension RangeReplaceableCollection {
/// Returns a collection containing, in order, the first instances of
/// elements of the sequence that compare equally for the keyPath.
func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> Self {
var unique = Set<T>()
return filter { unique.insert($0[keyPath: keyPath]).inserted }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment