Swift Equatable on a protocol

前端 未结 10 2101
时光说笑
时光说笑 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:32

    All people who say that you can't implement Equatable for a protocol just don't try hard enough. Here is the solution (Swift 4.1) for your protocol X example:

    protocol X: Equatable {
        var something: Int { get }
    }
    
    // Define this operator in the global scope!
    func ==(l: L, r: R) -> Bool {
        return l.something == r.something
    }
    

    And it works!

    class Y: X {
        var something: Int = 14
    }
    
    struct Z: X {
        let something: Int = 9
    }
    
    let y = Y()
    let z = Z()
    print(y == z) // false
    
    y.something = z.something
    pirnt(y == z) // true
    

    The only problem is that you can't write let a: X = Y() because of "Protocol can only be used as a generic constraint" error.

提交回复
热议问题