Hashable - overriding hashValue

When I put that in a playground, I get 'DataConversionOption' does not conform to protocol 'Hashable'. That goes away if Endian is Hashable and in that case you are relying on the compiler synthesizing Hashable for you.

Borrowing from a more knowledgable poster:

Your implementation violates this, because the automatically synthesized Hashable takes the associated values into account - DataConversionOption.encoding(.ascii).hashValue != DataConversionOption.encoding(.utf8).hashValue even though they are equal as far as Equatable is concerned.

That said, it seems to work in Sets, so :man_shrugging:

I believe the correct way to implement hashing now (the way you want it to work) would be

public func hash(into hasher: inout Hasher) {
    switch self {
        case .encoding:      hasher.combine(0)
        case .endian:        hasher.combine(1)
        case .nbrFromString: hasher.combine(2)
    }
}
2 Likes