3

Is there a way to use hash(into:) to compute the hashvalue of a struct/class whilst omitting certain properties from being used?

i.e.

struct CacheItem: Codable, Hashable {
    let val1: Int
    let val2: Int
    let date: Date = Date()

    func hash(into hasher: inout Hasher) {
        hasher.combine(val1) // leave out date for computing hash value
        hasher.combine(val2)
    }
}

I was hoping this would work:

let cache = Set<CacheItem>()
let item1 = CacheItem(val1: 0, val2: 0)
let item2 = CacheItem(val1: 0, val2: 0)

cache.insert(item1)
assert(cache.contains(item2))

However, it didn't work.

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.