Swift Equatable on a protocol

前端 未结 10 2114
时光说笑
时光说笑 2021-01-30 12:42

I don\'t think this can be done but I\'ll ask anyway. I have a protocol:

protocol X {}

And a class:

class Y:X {}
10条回答
  •  不思量自难忘°
    2021-01-30 13:25

    I came cross this same issue and I figured that the == operator can be implemented in the global scope (as it used to be), as opposed to a static func inside the protocol's scope:

    // This should go in the global scope
    
    public func == (lhs: MyProtocol?, rhs: MyProtocol?) -> Bool { return lhs?.id == rhs?.id }
    public func != (lhs: MyProtocol?, rhs: MyProtocol?) -> Bool { return lhs?.id != rhs?.id }
    

    Note that if you use linters such as SwiftLint's static_operator, you'll have to wrap that code around // swiftlint:disable static_operator to silent linter warnings.

    Then this code will start compiling:

    let obj1: MyProtocol = ConcreteType(id: "1")
    let obj2: MyProtocol = ConcreteType(id: "2")
    if obj1 == obj2 {
        print("They're equal.")
    } else {
        print("They're not equal.")
    }
    

提交回复
热议问题