Swift Equatable on a protocol

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

    Not sure why you need all instances of your protocol to conform to Equatable, but I prefer letting classes implement their equality methods.

    In this case, I'd leave the protocol simple:

    protocol MyProtocol {
        func doSomething()
    }
    

    If you require that an object that conforms to MyProtocol is also Equatable you can use MyProtocol & Equatable as type constraint:

    // Equivalent: func doSomething(element1: T, element2: T) where T: MyProtocol & Equatable {
    func doSomething(element1: T, element2: T) {
        if element1 == element2 {
            element1.doSomething()
        }
    }
    

    This way you can keep your specification clear and let subclasses implement their equality method only if required.

提交回复
热议问题