Removing duplicates whilst preserving order

Removing duplicates whilst preserving order @jcatterwaul / @jessycatterwaul (Removing duplicate elements from an array in Swift - Stack Overflow)

"If you put both extensions in your code, the faster Hashable version will be used when possible, and the Equatable version will be used as a fallback " —> Is it a compiler knowing what to use and when kind of thing?

public extension Sequence where Element: Hashable {
  var firstUniqueElements: [Element] {
    var set: Set<Element> = []
    return filter { set.insert($0).inserted }
  }
}

public extension Sequence where Element: Equatable {
  var firstUniqueElements: [Element] {
    reduce(into: []) { uniqueElements, element in
      if !uniqueElements.contains(element) {
        uniqueElements.append(element)
      }
    }
  }
}

Also any reason for why I am able to use this on a [Element] in the console but not in a file? :confused:

Yes. It’s the same concept as why you can put default implementations in protocol extensions, and have the compiler use specific implementations for concrete types. Hashable implements Equatable, so it’s essentially an “override”.

Sorry, can you clarify what you mean by that?

1 Like

Weird case of me being able to invoke the method on [Element] via po [Element].firstUniqueElements in the console but can’t seem to invoke it in a .swift file on [Element]

says has no member firstUniqueElements

Huh. Upload a playground and I’ll have a look!

RemoveDuplicates.playground.zip (1.6 KB)

Works in the playground, haha. Am sure I overlooked something in the actual project I was trying to use. Thanks for the help, Jessy!

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.