4

I have write an Array extension for distinct items

extension Array {
    func distinct<T: Equatable>() -> [T]{
        var unique = [T]()
        for i in self{
            if let item = i as? T {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}

And try to call this function like below

let words = ["pen", "Book", "pencile", "paper", "Pin", "Colour Pencile", "Marker"]
words.distinct()

But it give error "generic parameter 'T' could not be inferred swift"

Arun Kumar P
  • 820
  • 2
  • 12
  • 25
  • Have a look at http://stackoverflow.com/questions/24091046/unable-to-use-contains-within-a-swift-array-extension ... – Martin R Feb 09 '16 at 10:54

1 Answers1

14

You can get rid of this error by telling the compiler what you expecting:

let a: [String] = words.distinct()

The problem is that the compiler doesn't know what the generic T is. Much better solution would be tell the compiler that you define distinct function to all of the arrays where their Element is Equatable:

extension Array where Element : Equatable {
    func distinct() -> [Element]{
        var unique = [Element]()
        for i in self{
            if let item = i as? Element {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}
Greg
  • 25,317
  • 6
  • 53
  • 62