Created
January 1, 2018 14:04
-
-
Save stoeckley/5965f45cf6bc7853061e5d672ddd3577 to your computer and use it in GitHub Desktop.
best way to make this simple struct hashable?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// trying to keep this Hashable simple while minimizing collisions: | |
struct Simple: Hashable { | |
enum MyEnum: Int { | |
case a,b,c,d | |
} | |
let enumValue: MyEnum | |
let someInt: Int | |
} | |
extension Simple { | |
// the == is simple enough: | |
static func ==(lhs: Simple, rhs: Simple) -> Bool { | |
return lhs.enumValue == rhs.enumValue && lhs.someInt == rhs.someInt | |
// i've also seen using lhs.someInt.hashValue == rhs.someInt.hashValue here, but that seems unnecessary to me when a simple equality is available | |
} | |
// some hash options: | |
var hashValue: Int { return someInt ^ enumValue.rawValue } | |
var hashValue: Int { return someInt.hashValue ^ enumValue.rawValue.hashValue } | |
var hashValue: Int { return makeHashValue(int1: someInt, int2: enumValue.rawValue) } // see below | |
} | |
func makeHashValue(int1: Int, int2: Int) -> Int { | |
return int1.hashValue ^ (int2.hashValue &* 987654433) // using arbitrary big num to avoid collisions where both ints are == | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment