Skip to content

Instantly share code, notes, and snippets.

@dineybomfim
Last active August 19, 2023 13:26
Show Gist options
  • Save dineybomfim/90f1dd04fdf599c71f3ee21864460cc5 to your computer and use it in GitHub Desktop.
Save dineybomfim/90f1dd04fdf599c71f3ee21864460cc5 to your computer and use it in GitHub Desktop.
Swift unique functionality for Sequences / Collections, option to keep the first or the last occurrence of the duplicated element.
public extension Sequence where Element : Hashable {
/// Returns an array containing the unique elements from the sequence.
///
/// - Parameter keepLast: A boolean value indicating whether to keep the last occurrence of each duplicated element.
/// If `true`, the last occurrence is kept. If `false`, the first occurrence is kept. The default value is `false`.
/// - Returns: An array containing the unique elements from the sequence based on the `keepLast` behavior.
/// - Complexity: O(n), where `n` is the length of the sequence.
func unique(keepLast: Bool = false) -> [Element] {
guard !keepLast else { return reversed().unique(keepLast: false).reversed() }
var seen = Set<Element>()
return filter { seen.insert($0).inserted }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment