Swift Equatable on a protocol

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

    I would still advise against implementing == using polymorphism. It's a bit of a code smell. If you want to give the framework user something he can test equality with then you should really be vending a struct, not a protocol. That's not to say that it can't be the protocols that are vending the structs though:

    struct Info: Equatable {
      let a: Int
      let b: String
    
      static func == (lhs: Info, rhs: Info) -> Bool {
        return lhs.a == rhs.a && lhs.b == rhs.b
      }
    }
    
    protocol HasInfo {
      var info: Info { get }
    }
    
    class FirstClass: HasInfo {
      /* ... */
    }
    
    class SecondClass: HasInfo {
      /* ... */
    }
    
    let x: HasInfo = FirstClass( /* ... */ )
    let y: HasInfo = SecondClass( /* ... */ )
    
    print(x == y) // nope
    print(x.info == y.info) // yep
    

    I think this more efficiently communicates your intent, which is basically "you have these things and you don't know if they are the same things, but you do know they have the same set of properties and you can test whether those properties are the same." That is pretty close to how I would implement that Money example.

提交回复
热议问题