Swift Equatable on a protocol

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

    Swift 5.1 introduces a new feature into the language called opaque types
    Check code below
    that still gets back a X, which might be an Y, a Z, or something else that conforms to the X protocol,
    but the compiler knows exactly what is being returned

    protocol X: Equatable { }
    class Y: X {
        var something = 3
        static func == (lhs: Y, rhs: Y) -> Bool {
            return lhs.something == rhs.something
        }
        static func make() -> some X {
            return Y() 
        }
    }
    class Z: X {
        var something = "5"
        static func == (lhs: Z, rhs: Z) -> Bool {
            return lhs.something == rhs.something
        }
        static func make() -> some X {
            return Z() 
        }
    }
    
    
    
    let a = Z.make()
    let b = Z.make()
    
    a == b
    

提交回复
热议问题