Skip to content

Instantly share code, notes, and snippets.

@rcharlton
Last active July 12, 2024 14:31
Show Gist options
  • Save rcharlton/f860ebb0d9b90ab2e1945a0401a081b8 to your computer and use it in GitHub Desktop.
Save rcharlton/f860ebb0d9b90ab2e1945a0401a081b8 to your computer and use it in GitHub Desktop.
Swift enums, Equatable and Hashable
// Enums with associated values are not equatable...
enum MyEnum {
case a(number: Int)
case b
case c(text: String)
}
// We can define a hash based on the case or the case plus associated value.
extension MyEnum: Hashable {
public var hashValue: Int {
switch self {
case .a(let number):
return "a \(number)".hashValue
case .b:
return "b".hashValue
case .c(let text):
return "c \(text)".hashValue
}
}
/*
Alternative
public var hashValue: Int {
switch self {
case .a(let number):
return 0
case .b:
return 1
case .c(let text):
return 2
}
}
*/
}
extension MyEnum: Equatable {
public static func ==(lhs: MyEnum, rhs: MyEnum) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
let h1 = MyEnum.a(number: 1971).hashValue
let h2 = MyEnum.a(number: 13).hashValue
let h3 = MyEnum.b.hashValue
let h4 = MyEnum.c(text: "bibble").hashValue
var dict: [MyEnum: String] = [
MyEnum.a(number: 1971): "nineteenseventyone",
MyEnum.a(number: 13): "thirteen",
MyEnum.b: "b",
MyEnum.c(text: "bibble"): "wibble"
]
let equals1 = MyEnum.a(number: 13) == MyEnum.a(number: 13)
let equals2 = MyEnum.a(number: 13) == MyEnum.a(number: 007)
let equals3 = MyEnum.a(number: 13) == MyEnum.b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment