How can I implement a custom Swift class that conforms to Equatable for complex comparisons?

61 views Asked by At

I'm working on a Swift project where I have a custom class, CustomObject, and I need to compare instances of this class for equality based on specific properties. However, the comparison isn't straightforward, and I need to customize it.

Here's a simplified version of my CustomObject class:

class CustomObject {
    let id: Int
    let name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

I want to compare two instances of CustomObject based on the id property only. If two instances have the same id, I consider them equal. What's the best way to implement custom equality comparison for this class in Swift while conforming to the Equatable protocol?

I've tried conforming to Equatable and implementing the == operator, but I'm facing challenges when it comes to comparing the instances based on just one property.

1

There are 1 answers

0
Duncan C On

As Larme says, it's really simple. Just delcare that your struct conforms to Equatable, and then implement the == static function. For your example CustomObject, that would look like this:

class CustomObject: Equatable {
  let id: Int
  let name: String
  // We don't want to compare this property when testing for equality
  let randomValue = Int.random(in: 1...100)
  
  init(id: Int, name: String) {
    self.id = id
    self.name = name
  }
  
  static func ==(lhs: CustomObject, rhs: CustomObject) -> Bool {
    // Your custom comparison code goes here, and just needs to return a Bool
    return lhs.id == rhs.id
  }
}

(I added a property randomValue to show that your comparison code can ignore values that don't matter for your definition of equality. In your question you said you only want to check the id property, so that's what the implementation of == does above.)

You said "...I'm facing challenges when it comes to comparing the instances based on just one property." What challenges are you facing? If you need help with a specific problem we need details.