通过扩展自动合成 Swift 结构或枚举的 Equatable 一致性

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

Swift 文档说 Equatable 一致性的自动合成可用于结构和具有关联值的枚举,前提是在结构或枚举的原始定义中声明了一致性,而不是通过扩展,在这种情况下,必须提供 == 运算符的实现。

Documentation link

但是,下面的代码有效。

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

extension Point: Equatable {}

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

这个也是。

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

extension Outcome: Equatable {}

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

有谁知道这个功能的记录在哪里。

谢谢。

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

这意味着对于使用基本值类型的结构和枚举,无需声明明确符合 Equatable,因为它将由 Swift 本身自动提供所以

extension Point: Equatable {}

没有效果。第二个例子也是如此。

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.

这意味着只能在声明该值的模块内部遵守 Equatable 协议。您不能将它扩展到该模块之外以提供一致性。

您可以使用此参考资料了解更多详情 https://swiftdoc.org/v3.0/protocol/equatable/

综合提案 (SE-0185) 与您链接的文档有所不同:

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).

根据提案,在同一个文件中的扩展中声明一致性也会自动生成所需的成员,这符合实际行为。如果您在与类型不同的文件中声明扩展名,您应该会看到一条错误消息:

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