Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to add != to make Equatable works?

Tags:

swift

Why do I have to add != to make the comparison correct?

import UIKit

class Person: NSObject {
    var name: String
    var age: Int

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

extension Person {
    static func ==(lhs: Person, rhs: Person) -> Bool {
        return lhs.name == rhs.name && lhs.age == rhs.age
    }
    static func !=(lhs: Person, rhs: Person) -> Bool {
        return !(lhs == rhs)
    }
}

let first = Person(name: "John", age: 26) 
let second = Person(name: "John", age: 26)

/**
 * return false (which is correct) when we implement != function. But,
 * it will return true if we don't implement the != function.
 */
first != second 

Update: So I got why I had to add != function to make it work. it's because the class inherit the NSObject which uses isEqual method behind the scene. But why does adding != function make it work? Any explanation here?

like image 704
Edward Anthony Avatar asked Sep 20 '25 18:09

Edward Anthony


1 Answers

NSObject conforms to Equatable but uses its own isEqual method and in terms of isEqual both instances are not equal. NSObject calls == only if your form of != is implemented, which contains ==.

If you delete NSObject (and add Equatable) the implementation of == works as expected.

The recommended way for NSObject is to override isEqual with a custom implementation and omit == (and !=).

like image 114
vadian Avatar answered Sep 22 '25 13:09

vadian