Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a equatable protocol needs to be defined outside the class?

Tags:

swift

hashable

When i implement the Hashable protocol. a equatable protocol function is needed to be defined outside the class as follow. As follow.

func ==(lhs: Swap, rhs: Swap) -> Bool {
    return (lhs.cookieA == rhs.cookieA && lhs.cookieB == rhs.cookieB) ||
        (lhs.cookieB == rhs.cookieA && lhs.cookieA == rhs.cookieB)
}

class Swap: Printable,Hashable {
    var cookieA: Cookie
    var cookieB: Cookie

    init(cookieA: Cookie, cookieB: Cookie) {
        self.cookieA = cookieA
        self.cookieB = cookieB
    }
    var hashValue: Int {
    return cookieA.hashValue ^ cookieB.hashValue
    }

    var description: String {
    return "swap \(cookieA) with \(cookieB)"
    }
}

It is just a bit weird for me. In the above example func == should be belong to the class Swap. So why we need to declare the func == outside the class??

like image 934
Siu Chung Chan Avatar asked Feb 03 '26 05:02

Siu Chung Chan


2 Answers

Mainly because it's a function and not a method. Functions are independent on classes so it makes no sense to scope them inside class declarations.

The protocol could have been designed with methods, e.g. using a obj1.isEqualTo(obj2) method but a function is less sensitive to nil problems. If obj1 were nil, the method would fail.

like image 184
Sulthan Avatar answered Feb 04 '26 21:02

Sulthan


I wouldn't read too much into it. I think it's just a simple design decision. Yes, in many languages operator overloads are methods on the left-hand-side operand and that's fine, but defining operators as functions probably gives you a bit more flexibility so they decided to make them all functions.

like image 27
radex Avatar answered Feb 04 '26 20:02

radex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!