代码之家  ›  专栏  ›  技术社区  ›  Yogurt

在两个协议对象上使用equals

  •  0
  • Yogurt  · 技术社区  · 6 年前

    理想情况下,我会让服务器实现可平等协议,但我遇到了问题。这是我的密码

    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 回复  |  直到 6 年前
        1
  •  0
  •   Cristik    6 年前

    如果将函数设为泛型,则问题将消失:

    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 不符合 (听起来很奇怪)。这意味着声明接收协议的函数不能通过向其传递协议来调用,您需要告诉编译器您传递的协议的具体实现。