SequenceExtensions.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Argument Parser open source project
  4. //
  5. // Copyright (c) 2020 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. extension Sequence where Element: Hashable {
  12. /// Returns an array with only the unique elements of this sequence, in the
  13. /// order of the first occurrence of each unique element.
  14. func uniquing() -> [Element] {
  15. var seen = Set<Element>()
  16. return self.filter { seen.insert($0).0 }
  17. }
  18. /// Returns an array, collapsing runs of consecutive equal elements into
  19. /// the first element of each run.
  20. ///
  21. /// [1, 2, 2, 2, 3, 3, 2, 2, 1, 1, 1].uniquingAdjacentElements()
  22. /// // [1, 2, 3, 2, 1]
  23. func uniquingAdjacentElements() -> [Element] {
  24. var iterator = makeIterator()
  25. guard let first = iterator.next()
  26. else { return [] }
  27. var result = [first]
  28. while let element = iterator.next() {
  29. if result.last != element {
  30. result.append(element)
  31. }
  32. }
  33. return result
  34. }
  35. }