Created
March 7, 2023 13:25
-
-
Save johnkodes/826be0b197b7462d46feed4d5d49ebb1 to your computer and use it in GitHub Desktop.
Unique elements from Sequence
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
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