Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 339
Bobj-C Avatar asked May 06 '16 09:05

Bobj-C


People also ask

How do you compare two structured objects?

In the Object Oriented World, generally, all Objects are unique to each other. So, how I could compare two objects? With the Equatable protocol you can implement the static func == . Here you can define how two object of the same class could be equal when you use the operator == .

Can 2 structures be compared?

yes,we can compare by using thir addresses. If the 2 structures variable are initialied with calloc or they are set with 0 by memset so you can compare your 2 structures with memcmp. It is possible to use memcmp if: 1) the structs contain no floating-point fields.

How do I compare two objects in Swift?

The == Operator In Swift, the equals operator has almost the same goal it has in other object-oriented programming languages: It compares objects by reference. First of all, keep in mind that the expected boolean depends on what kind of things you're comparing. In Swift, variables can be value types or reference types.


1 Answers

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 }
like image 76
Daniel Avatar answered Sep 30 '22 18:09

Daniel