[swift-evolution] [Review] SE-0185 - Synthesizing Equatable and Hashable conformance

Jordan Rose jordan_rose at apple.com
Thu Aug 10 16:58:07 CDT 2017



> On Aug 10, 2017, at 14:48, Tony Allevato <tony.allevato at gmail.com> wrote:
> 
> On Thu, Aug 10, 2017 at 11:05 AM Jordan Rose <jordan_rose at apple.com <mailto:jordan_rose at apple.com>> wrote:
> [Proposal: https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md <https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md>]
> 
> Hi, Tony. Glad to see this back again!
> 
> Overall I'm an enthusiastic +1. The restrictions and future work you've listed make sense, and I think this is the right starting place. I just have one thing I'd want to clarify:
> 
>> Any user-provided implementations of == or hashValue will override the default implementations that would be provided by the compiler.
> 
> Does this include implementations in (possibly constrained) protocol extensions? I assume yes, but that's probably worth calling out explicitly. Still, it could be confusing to some users.
> 
> Yes, manual implementations added in extensions override the compiler-synthesized default:
> 
> Without constraints:
> (swift) struct Foo: Equatable { let x: Int }
> (swift) Foo(x: 5) == Foo(x: 6)
> // r0 : Bool = false
> (swift) Foo(x: 5) == Foo(x: 5)
> // r1 : Bool = true
> (swift) extension Foo { static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.x % 2 == rhs.x % 2 } }
> (swift) Foo(x: 5) == Foo(x: 6)
> // r2 : Bool = false
> (swift) Foo(x: 5) == Foo(x: 7)
> // r3 : Bool = true
> 
> With constraints:
> (swift) struct Foo<T: Equatable>: Equatable { let t: T }
> (swift) extension Foo where T == String { static func ==(lhs: Foo<T>, rhs: Foo<T>) -> Bool { return lhs.t.characters.count == rhs.t.characters.count } }
> (swift) Foo(t: "foo") == Foo(t: "bar")
> // r0 : Bool = true
> (swift) Foo(t: 5) == Foo(t: 7)
> // r1 : Bool = false
> 
> I can update the text to make this explicit.

Ah, that's not quite the example I meant, and your example isn't a correct demonstration for the REPL. If you want to test the == that's used in the Equatable conformance, you have to call a function that's generic on Equatable.

Anyway, this is the example I meant:

protocol Annoying {}
extension Annoying {
  static func ==(lhs: Self, rhs: Self) -> Bool {
    print("annoying")
    return true
  }
}
struct Foo: Equatable, Annoying {
  let x: Int
}
print(Foo(x: 5) == Foo(x: 6))

I think the correct behavior here is to call the version from Annoying, but I can also see how that would be surprising.

Jordan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170810/e7308a76/attachment.html>


More information about the swift-evolution mailing list