I'd like to have an enum with two cases with a Hashable associated type each conform to Hashable, like so:
enum WordOrNumber {
case Word(String)
case Number(Int)
}
The first idea I had for hashing was the following:
extension WordOrNumber: Hashable {
var hashValue: Int {
switch self {
case let .Word(word):
return word.hashValue & ~1 // ends in 0
case let .Number(number):
return number.hashValue | 1 // ends in 1
}
}
}
What I'm not sure about, is how this will interact with buckets in Swift's Dictionary and Set implementations.
Is it be better to differentiate the two cases by the LSB or MSB, or by a bit somewhere in the middle?
I assume it doesn't make any difference to shift the hashValues left by one and then adding 1, or not, but I would be interested to know if this isn't the case.
EDIT: I just tested this, and it looks like the hashValue of an Int is the value itself. This is obviously a problem, since you often get ints in succession, like in an enum Bla: Int {}. So my new and improved(?) hashValue is:
extension WordOrNumber: Hashable {
var hashValue: Int {
switch self {
case let .Word(word): // ends in 0
return word.hashValue << 1
case let .Number(number): // ends in 1
return number.hashValue << 1 &+ 1
}
}
}
The above question about LSB and MSB still stands.