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??
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With