Search code examples
iosswiftclass-extensions

Swift contains extension for Array


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


Solution

  • 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)