Bobj-C Bobj-C - 7 months ago 18
Swift Question

Compare 2 structs/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 error: binary operator '==' cannot be applied to operands of type 'A' and 'B'

is there any way to achieve this ?

Answer

you have to define the equality function with two generic types to allow different types to be compared, like this:

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