'Is there an error prone way to exclude certain properties from struct during equality comparison without writting our own == function?

We like the auto equality behavior of struct, by just simply conform Equatable protocol.

Sometimes, we would like to exclude some properties out from struct equality comparison.

Currently, this is the method we are using.

struct House: Equatable {
    var field_0: String
    var field_1: String
    ...
    var field_50: String

    static func == (lhs: House, rhs: House) -> Bool {
        if lhs.field_0 != rhs.field_0 { return false }
        if lhs.field_1 != rhs.field_1 { return false }
        ...
        if lhs.field_48 != rhs.field_48 { return false }
        // Ommit field_49
        if lhs.field_50 != rhs.field_50 { return false }

        return true
    }
}

But, such methodology is pretty error prone, especially when we add in new field in the struct.

Is there a way to exclude certain properties fields from equality comparison, without writing our own == function?



Solution 1:[1]

Is there a way to exclude certain properties fields from equality comparison, without writing our own == function?

No. At present, the only alternative to automatic synthesis of Equatable conformance is good old fashioned writing code.

Solution 2:[2]

There is a solution using Swift Property Wrapper feature actually. It's described here.

Basically what you need is to define next property wrapper

@propertyWrapper
struct EquatableNoop<Value>: Equatable {
    var wrappedValue: Value

    static func == (lhs: EquatableNoop<Value>, rhs: EquatableNoop<Value>) -> Bool {
        true
    }
}

And use it like next

struct Test: Equatable {
    var a: Int

    @EquatableNoop
    var b: () -> Void
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matt
Solution 2 Olexandr Stepanov