Compare 2 structures / Objects implement the same protocol?

let's say I have the following:

protocol P : Equatable { var uniqueID : Int { get } } struct A : P { var uniqueID = 1 } struct B : P { var uniqueID = 2 } func ==<T : P>(lhs:T , rhs:T) -> Bool { return lhs.uniqueID == rhs.uniqueID } 

Now when I write the following:

  let a = A() let b = B() let c = a == b 

I got an error : the binary operator '==' cannot be applied to operands of type "A" and "B"

Is there any way to achieve this?

+6
source share
1 answer

you need to define an equality function with two universal types so that you can compare different types, for example:

 func ==<T: P, T2: P>(lhs: T , rhs: T2) -> Bool { return lhs.uniqueID == rhs.uniqueID } 
+10
source

All Articles