Dejan Skledar Dejan Skledar - 2 months ago 9
Swift Question

Array extension generic Equatable - "Cannot invoke '==' with ..."

I am trying to write an extension of the Swift Array, but I am getting some wierd errors as I try to compile.

My code:

extension Array
{
func itemExists<T: Equatable>(item: T) -> Bool
{
for elt in self
{
if elt == item
{
return true
}
}
return false
}
}


Error:


Cannot invoke '==' with an argument list of type '(T, T)'


Why am I getting this? I am using the
Equatable
protocol?

What I also tried was:

extension Array
{
func itemExists<T: Equatable>(item: T) -> Bool
{
var array:[T] = self
for elt in array
{
if elt == item
{
return true
}
}
return false
}
}


Where I got a funny error:


'T' is not identical to 'T'


What am I missing? I read the Apple Documentation about it but I am already using the
Equatable
protocol to be able to use the
==
operator on
'T'
.

Answer

I found my solution.

As MartinR alreary said, my method would only be applicable to arrays of Equatable elements, and you cannot write a method on a generic type that is more restrictive on the template.

There are two ways - writing my code as a function and not as an extension, or use this trick:

extension Array
{
    func itemExists<T: Equatable>(item: T) -> Bool
    {
        return self.filter({$0 as? T == item}).count > 0
    }
}
Comments