A Set
is a collection of unique objects, and equality is based on comparison with ==
. Equal objects must have the same hash value, but not the other way around: Distinct objects can have the same hash value. (A simple example: There are 264 possible hash values, but infinitely many strings. So there are necessarily distinct strings with the same hash value.)
Hashable collections (like Set
and Dictionary
) use the hash value in their implementation (e.g. to put different objects into different “buckets”) but they never use the hash value alone to determine equality.
The default implementation of ==
compares all (stored) properties for equality. Therefore, in your case, if item1
and item2
have the same val1
and val2
but different date
then they are different objects, even if they have the same hash value.
If you want that objects with same val1
and val2
but different date
are considered equal then you must implement ==
yourself:
struct CacheItem: Codable, Hashable {
// ...
static func ==(lhs: CacheItem, rhs: CacheItem) -> Bool {
return lhs.val1 == rhs.val1 && lhs.val2 == rhs.val2
}
}
Then
var cache = Set<CacheItem>()
let item1 = CacheItem(val1: 0, val2: 0)
let item2 = CacheItem(val1: 0, val2: 0)
cache.insert(item1)
print(cache.contains(item2))
will always print true
.