0

I have this function that dedups arrays by returning an array of its set.

func dedup<T: Hashable>(_ a: [T]) -> [T] {
    return Array(Set(a))
}

let dirty = ["apple", "apple", "kiwi", "mango"]
let clean = dedup(dirty)

print(clean)

However, I can't figure out how to make this an extension of Array.

extension Array where Element: Hashable {

    static func deduped() -> Array {
        return Array(Set<Element>(self))
    }

}

The error I get is that self does not conform to expected type Sequence.

lurning too koad
  • 2,698
  • 1
  • 17
  • 47
  • 1
    But note this is a poor algorithm as your array will be both deduped and shuffled. – matt Nov 17 '19 at 20:18

1 Answers1

2

deduped() must be an instance method, and – more descriptive and not related to the issue – return [Element] rather than Array

extension Array where Element: Hashable {

    func deduped() -> [Element] {
        return Array(Set(self))
    }
}

However here are more efficient ways to remove duplicates, my favorite is

extension Array where Element: Hashable {
    func deduped() -> [Element] {
        var seen = Set<Element>()
        return filter{ seen.insert($0).inserted }
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361