Skip to content

Instantly share code, notes, and snippets.

@stoeckley
Created January 1, 2018 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stoeckley/5965f45cf6bc7853061e5d672ddd3577 to your computer and use it in GitHub Desktop.
Save stoeckley/5965f45cf6bc7853061e5d672ddd3577 to your computer and use it in GitHub Desktop.
best way to make this simple struct hashable?
// 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