0

I overloaded the == operator on a class. Then a child class also overloads the == operator. My understanding is that both == and != are supposed to call the same == function. However, when running tests, == calls the function on the child class, yet != calls the function on the parent class. This is bizarre. I would expect the same behavior for both == and !=.

class Description: Equatable {
    var id : Int = IdFactory.id()  
    static func == (lhs: Description, rhs: Description) -> Bool {
        assertionFailure("Child Description must override == method.")
        return false
    }
}

class LineDescription : Description {
    var track = 0

    static func == (lhs: LineDescription, rhs: LineDescription) -> Bool {
        if lhs.track != rhs.track { return false }
        return true
    }
}

import XCTest
class LineDescriptionTest: XCTestCase {
    func testEquality(){
        let ld = LineDescription()
        ld.track = 9
        let ld2 = LineDescription()
        ld2.track = 9
        XCTAssert(ld == ld2) //<--Calls child == function
        ld2.track = 1
        XCTAssert(ld != ld2) //<--Calls parent != function
    }
}
dmann200
  • 529
  • 4
  • 11
  • 1
    Possible duplicate of [Swift: Overriding == in subclass results invocation of == in superclass only](https://stackoverflow.com/questions/28793218/swift-overriding-in-subclass-results-invocation-of-in-superclass-only). – Martin R Aug 20 '19 at 19:38
  • 1
    See also [Implement Equatable protocol in a class hierarchy](https://forums.swift.org/t/implement-equatable-protocol-in-a-class-hierarchy/13844) in the Swift Forum, and [How to properly implement the Equatable protocol in a class hierarchy?](https://stackoverflow.com/questions/39909805/how-to-properly-implement-the-equatable-protocol-in-a-class-hierarchy) – Martin R Aug 20 '19 at 19:40

0 Answers0