swiftswift-structs

Is there way to define compare (`==`) function automatically for `struct` in Swift?


Let's assume we have a pretty big struct in Swift:

struct SuperStruct {
    var field1: Int = 0
    var field2: String = ""
    // lots of lines...
    var field512: Float = 0.0
}

.. and then we need to implement Equatable protocol:

extension SuperStruct: Equatable {
}

func ==(lhs: SuperStruct, rhs: SuperStruct) -> Bool {
    return
        lhs.field1 == rhs.field1 &&
        lhs.field2 == rhs.field2 &&
        // lots of lines...
        lhs.field512 == rhs.field512
}

... and we need to write lots of lines of stupid code. Is there a way "to ask" compiler "to do" it for us?


Solution

  • In Swift 4.1, Equatable/Hashable types now synthesize conformance to Equatable/Hashable if all of the types' members are Equatable/Hashable

    SE-0185

    Synthesizing Equatable and Hashable conformance

    Developers have to write large amounts of boilerplate code to support equatability and hashability of complex types. This proposal offers a way for the compiler to automatically synthesize conformance to Equatable and Hashable to reduce this boilerplate, in a subset of scenarios where generating the correct implementation is known to be possible.

    https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md