在两个协议对象上使用均等

时间:2018-08-16 20:54:43

标签: swift operator-overloading protocols equatable

理想情况下,我希望服务器实现Equatable协议,但我遇到了问题。这是我的代码

protocol Server {
    var ipAddress: String { get }
    // simplified for this question
}

func ==<T:Server>(lhs: T, rhs: T) -> Bool {
    return lhs.ipAddress == rhs.ipAddress
}

func !=<T:Server>(lhs: T, rhs: T) -> Bool {
    return lhs.ipAddress != rhs.ipAddress
}

func ==<T:Server, U:Server>(lhs: T, rhs: U) -> Bool {
    return lhs.ipAddress == rhs.ipAddress
}

func !=<T:Server, U:Server>(lhs: T, rhs: U) -> Bool {
    return lhs.ipAddress != rhs.ipAddress
}

func doSomething(server0: Server, server1: Server) {
    // I want to compare to Server objects

    // !!! Compile Error !!!
    // Binary operator '==' cannot be applied to two 'Server' operands
    guard server0 == server1 else {
        print("SAME BAD")
        return
    }

    print("DO stuff")
}

最终,我只想将抽象协议对象相互比较。其他大多数示例都在比较具体类型。

我为尝试这样做还是为之疯狂? :P

1 个答案:

答案 0 :(得分:0)

如果使函数通用,您的问题将消失:

func doSomething<T1: Server, T2: Server>(server0: T1, server1: T2) {

这是必需的,因为在Swift protocols don't conform to base protocols, not even to themselves中。添加泛型子句会根据调用时传递的参数将功能从抽象变为具体。

以下代码会发生相同的错误:

struct A: Server {
    let ipAddress: String = ""
}

let server1: Server = A()
let server2: Server = A()
print(server1 == server2) // Binary operator '==' cannot be applied to two 'Server' operands

错误的起因相同:Server不符合Server(听起来可能很奇怪)。这意味着声明接收协议的函数不能通过将协议传递给它来调用,您需要告诉编译器所传递的协议的具体实现。