Search code examples
arraysswiftswift3equatable

Check if Swift array contains instance of object


How does one check if a Swift array contains a particular instance of an object? Consider this simple example:

class Car {}

let mazda = Car()
let toyata = Car()

let myCars = [mazda, toyata]

myCars.contains(mazda) // ERROR!

My investigations have let me to the conclusion that the Car class must adopt the Equatable protocol. It seems to be the case:

class Car: Equatable {
    static func ==(lhs: Car, rhs: Car) -> Bool {
        return true
    }
}

Then myCars.contains(mazda) does indeed return true.

However, the implementation of == is obviously not what I want. What I really want it to return is the answer to the question: Are lhs and rhs the same Car instances?

Is it really that complicated?

Thanks!


Solution

  • Use the identity operator

    static func ==(lhs: Car, rhs: Car) -> Bool {
       return lhs === rhs
    }
    

    Or even without Equatable

    myCars.contains{ $0 === mazda }
    

    Edit: But a better solution is to implement equality rather than identity, for example a vendor and type property in the class

    static func ==(lhs: Car, rhs: Car) -> Bool {
       return lhs.vendor == rhs.vendor && lhs.type == rhs.type
    }