Skip to content

Instantly share code, notes, and snippets.

@dineybomfim
dineybomfim / UniqueSequence.swift
Last active August 19, 2023 13:26
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() }