My custom structure implements the Hashable Protocol. However, when hash collisions occur while inserting keys in a Dictionary
, they are not auto
I think you have all the pieces of the puzzle you need -- you just need to put them together. You have a bunch of great sources.
Hash collisions are okay. If a hash collision occurs, objects will be checked for equality instead (only against the objects with matching hashes). For this reason, objects' Equatable
conformance needs to be based on something other than hashValue
, unless you are certain that hashes cannot collide.
This is the exact reason that objects that conform to Hashable
must also conform to Equatable
. Swift needs a more domain-specific comparison method for when hashing doesn't cut it.
In that same NSHipster article, you can see how Mattt implements isEqual:
versus hash
in his example Person
class. Specifically, he has an isEqualToPerson:
method that checks against other properties of a person (birthdate, full name) to determine equality.
- (BOOL)isEqualToPerson:(Person *)person {
if (!person) {
return NO;
}
BOOL haveEqualNames = (!self.name && !person.name) || [self.name isEqualToString:person.name];
BOOL haveEqualBirthdays = (!self.birthday && !person.birthday) || [self.birthday isEqualToDate:person.birthday];
return haveEqualNames && haveEqualBirthdays;
}
He does not use a hash value when checking for equality - he uses properties specific to his person class.
Likewise, Swift does not let you simply use a Hashable
object as a dictionary key -- implicitly, by protocol inheritance -- keys must conform to Equatable
as well. For standard library Swift types this has already been taken care of, but for your custom types and class, you must create your own ==
implementation. This is why Swift does not automatically handle dictionary collisions with custom types - you must implement Equatable
yourself!
As a parting thought, Mattt also states that you can often just do an identity check to make sure your two objects are at different memory address, and thus different objects. In Swift, that would like like this:
if person1 === person2 {
// ...
}
There is no guarantee here that person1
and person2
have different properties, just that they occupy separate space in memory. Conversely, in the earlier isEqualToPerson:
method, there is no guarantee that two people with the same names and birthdates are actually same people. Thus, you have to consider what makes sense for you specific object type. Again, another reason that Swift does not implement Equatable
for you on custom types.