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 ?
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 == .
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With