[swift-evolution] Universal Equatability, Hashability, and Comparability

Russ Bishop xenadu at gmail.com
Wed Mar 9 12:45:34 CST 2016


> On Mar 8, 2016, at 5:12 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> - Function types in Swift do not provide a ready equality operation. We could provide a default implementation that always returns 'false', perhaps.
> 
> I think this sort of puts the lie to the idea.
> 
> We can always provide *a* definition of equality, but I suspect it will often be an *incorrect* definition. That's why you had to suggest functions should always be false: you cannot (without more effort than you want to spend) provide a correct definition of equality for it.
> 

+1 to this. Having come from years of writing C# code, having every type implement Equatable and Hashable just led to a lot of useless magic because there are different definitions of equality and the default implementation was often not what you wanted, or your implementation was accidentally broken but you didn’t realize it.

> 
> * * *
> 
> Auto-deriving is a different story, though, especially if it's opt-in (you have to say `deriving Equatable`). There, you presumably have looked at the default semantics and determined they're appropriate for your type.
> 
> But I think it's clear that derived conformances should eventually be a user-accessible feature. We already derive RawRepresentable and ErrorType on enums. (We also derive initializers on some types, but that's arguably a separate feature.) I think it's clear that Swift ∞ ought to allow you to derive protocol conformances; it's just a matter of scheduling.
> 
> So I think that what we ought to do is this:
> 
> • Make a best guess at what Swift ∞ would want you to do to invoke the user-specified derivation logic for an arbitrary protocol—implicit derivation or something marked by a keyword.
> • Think about whether derived conformances of Equatable, Hashable, and/or Comparable are urgent enough that we should implement them before the general feature.
> • If so, design these features along the lines of what we would expect the eventual user-specified derivation feature to use.

We can also allow opt-in by adopting a protocol, eg `struct SimpleStruct: DefaultEquatable`. DefaultEquatable would tell the compiler to auto-generate an equatable implementation. Similar for DefaultHashable.

In the C# world you’d actually do something like this with an attribute. I know user-defined attributes aren’t on the table right now but some more built-in ones would be sufficient: @defaultEquatable, @defaultHashable, etc. 
They could even take a list of properties to ignore if such a feature were useful: `@defaultEquatable(ignored: [currentDate, randomInt])`.


Russ


More information about the swift-evolution mailing list