Arun Kumar P Arun Kumar P - 1 month ago 10
iOS Question

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"

Answer

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
    }
}