为什么需要在类外定义等同协议?

Siu*_*han 2 hashable swift

当我实现Hashable协议时.需要在类外定义一个等同的协议函数,如下所示.如下.

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)"
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我来说有点奇怪.在上面的例子中,func ==应该属于Swap类.那么为什么我们需要声明类外的func ==?

Sul*_*han 7

主要是因为它是一种功能,而不是一种方法.函数在类上是独立的,因此将它们放在类声明中是没有意义的.

协议可以使用方法设计,例如使用obj1.isEqualTo(obj2)方法但功能对nil问题不太敏感.如果obj1nil,该方法将失败.