Search code examples
swifthashable

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


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??


Solution

  • 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.