Swift contains extension for Array

Gralex picture Gralex · Jun 6, 2014 · Viewed 13.4k times · Source

I'm trying to add an extension method in Array like so:

extension Array {
    func contains(obj: T) -> Bool {
        let filtered = self.filter {$0 == obj}
        return filtered.count > 0
    }
}

But self.filter {$0 == obj} don't work. Compiler error:

could not find an overload for '==' that accepts the supplied arguments

Answer

atermenji picture atermenji · Jul 21, 2014

you don't actually need to write an extension, you can use the global func contains from the Swift library:

contains([1,2,3], 1)