[swift-evolution] Custom equality/hash for Sets

Joe Groff jgroff at apple.com
Fri Feb 19 12:58:28 CST 2016


> On Feb 19, 2016, at 7:45 AM, Sean Heber via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I constantly run into this and I’m working on a Swift-only game project where I use value types as much as possible - but even there I find myself having to implement Equatable and Hashable on classes all the time just to add an == operator that just calls through to === / ObjectIdentity to get it to the work the way I need it to. Swift does a pretty good job eliminating boilerplate, but this is one area where it seems to stick out.
> 
> It might be potentially awesome to be able to do something like this and have the compiler generate an == function for me using the given function:
> 
> class MyClass: Equatable(===) {
> // etc..
> }
> 
> But there are likely ramifications to this that I’m not really thinking about.

You could provide a default implementation constrained on `AnyObject`:

func ==<T: AnyObject>(x: T, y: T) -> Bool { return x === y }

Then you just need to declare `class MyClass: Equatable` to pick up that implementation for Equatable conformance.

-Joe


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


More information about the swift-evolution mailing list