Let's say we have a struct Person
,
struct Person {
var name: String
var age: Int
}
Now you can conform the Equatable protocol
in it like,
extension Person: Equatable {
public static func == (lhs: Person, rhs: Person) -> Bool {
let children1 = Mirror(reflecting: lhs).children
let children2 = Mirror(reflecting: rhs).children
for child1 in children1 {
let value1 = child1.value
if let value2 = children2.first(where: { $0.label == child1.label })?.value {
if String(describing: value1) != String(describing: value2) {
return false
}
} else {
return false
}
}
return true
}
}
In the above code, I'm comparing String
values of both value1
and value2
. This is not exactly the right way to do it. But I had to since value1
and value2
are of Any
type and hence cannot be compared directly. So, the solution might not work for custom types inside Person
.
This is just a way out in case you don't want to compare all the properties individually.
Usage:
let p1 = Person(name: "Name1", age: 10, designation: nil)
let p2 = Person(name: "Name1", age: 10, designation: "SE")
print(p1 == p2)