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 {}
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 protocol
s that are vending the struct
s 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.