-1

I have a class with Equatable protocol implementation. I know that 2 objects of this class are equal if all their inner variables are equal. Objects may contain arrays. Currently I hardcode each value pair comparison which is not agile.

If there is a way to implement such comparison by iterating through the property list? For example with Mirror (reflection)?

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
  • What can be the case where you don't know the properties in the object where you're conforming Equatable. Kindly specify the scenario as well. – PGDev Aug 09 '19 at 07:40
  • the list is big and is not finished. So otherwise I need to rewrite `==` operator each time I remove or add a new property and it is not agile – Vyachaslav Gerchicov Aug 09 '19 at 07:46

1 Answers1

1

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)
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • What to do if `Person` contains `var data: [PersonData]`, where `PersonData` implements `Equatable` via the same way? I try create `[PersonData]` with one element (but such elements contain different inner data) and your code says that 2 `Person` are equal – Vyachaslav Gerchicov Aug 09 '19 at 08:42