Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic parameter could not be inferred swift

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"

like image 701
Arun Kumar P Avatar asked Dec 08 '22 23:12

Arun Kumar P


1 Answers

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
    }
}
like image 118
Greg Avatar answered Dec 25 '22 09:12

Greg