Home > other >  Automatic synthesis of Equatable conformance for Swift struct or enum through an extension
Automatic synthesis of Equatable conformance for Swift struct or enum through an extension

Time:12-08

Swift docs say that automatic synthesis of Equatable conformance is available for structs, and enums with associated values, only if conformance is declared in the original definition of the struct or enum, and not through an extension, in which case an implementation of the == operator must be provided.

Documentation link

However, the following code works.

struct Point {
    var x: Double
    var y: Double
}

extension Point: Equatable {}

print(Point(x: 10, y: 10) == Point(x: 5, y: 5))   // prints false

So does this.

enum Outcome {
    case success
    case failure(reason: String)
}

extension Outcome: Equatable {}

print(Outcome.failure(reason: "Chance") == Outcome.failure(reason: "Chance"))   // prints true

Does anyone know where this feature is documented.

Thanks.

CodePudding user response:

The proposal (SE-0185) for the synthesis says something different to the documentation you linked:

Users must opt-in to automatic synthesis by declaring their type as Equatable or Hashable without implementing any of their requirements. This conformance must be part of the original type declaration or in an extension in the same file (to ensure that private and fileprivate members can be accessed from the extension).

According to the proposal, declaring conformance in extensions in the same file also automatically generates the required members, which is in line with the actual behaviour. If you declare the extension in a different file from the type, you should see an error message:

Extension outside of file declaring struct 'Point' prevents automatic synthesis of '==' for protocol 'Equatable'

CodePudding user response:

automatic synthesis of Equatable conformance is available for structs, and enums with associated values

This means for structs and enums that use basic value types there is no need to declare explicit conformance to Equatable since it will be provided automatically by Swift itself So

extension Point: Equatable {}

has no effect. Same can be said about second example.

conformance is declared in the original definition of the struct or enum, and not through an extension, in which case an implementation of the == operator must be provided.

This means conformance to Equatable protocol can only be done inside the module where the value is declared. You can not extend it out side of that module to provide conformance.

You can use this reference for more details https://swiftdoc.org/v3.0/protocol/equatable/

  • Related