[swift-evolution] Custom equality/hash for Sets

Sean Heber sean at fifthace.com
Fri Feb 19 09:45:53 CST 2016


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.

l8r
Sean


> On Feb 19, 2016, at 9:13 AM, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Needing a Set of identical reference objects, i.e. comparing with ===, has come up quite regularly in the projects I have worked on (as well as indexing by identity in a Dictionary). This might be mitigated in Swift due to a more prominent role of value types but I would still expect it to be useful.
> 
> -Thorsten 
> 
>> Am 19.02.2016 um 05:39 schrieb Dmitri Gribenko via swift-evolution <swift-evolution at swift.org>:
>> 
>> On Thu, Feb 18, 2016 at 2:58 PM, Jacob Bandes-Storch via
>> swift-evolution <swift-evolution at swift.org> wrote:
>>> Would it make sense for the standard library Set to provide variants (or
>>> parallel versions of the same data structure) that take custom hashValue/==
>>> implementations at init time (functions taking in Elements), rather than
>>> relying on Hashable/Comparable protocols?
>> 
>> It might make sense, but we should keep in mind that doing this will
>> prevent inlining of hashValue/== in most cases.
>> 
>> Dmitri
>> 
>> -- 
>> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
>> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list