Search code examples
iosswiftcontains

Is it possible to use Contains on an array of objects using one equatable object field?


Giving the following object as an example, is it possible to check if an array of this object contains specific numeric number based on the "number" field alone using the array ".contains" method ?

struct AvailableDay {
    
    var someField : someObject
    var number : Int
  }

The array:

var availableDay : [AvailableDay]


availableDay.contains(...) /*Just to absolutely clarify what I meant by "contains".*/

Solution

  • Use contains(where:

    availableDay.contains(where: { $0.number == yourDesiredNumber})
    

    Alternatively, you can override the equitable conformance to check only for the number property, like this:

    extension AvailableDay: Equatable {
        static func == (lhs: AvailableDay, rhs: AvailableDay) -> Bool { lhs.number == rhs.number }
    }