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"
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With