Skip to content

Instantly share code, notes, and snippets.

@mathewsanders
Created October 24, 2016 19:14
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 mathewsanders/053ed75e97823bf69ce9ee08d707ec9c to your computer and use it in GitHub Desktop.
Save mathewsanders/053ed75e97823bf69ce9ee08d707ec9c to your computer and use it in GitHub Desktop.
Hashable enum
enum FooBar: Hashable {
case foo(String)
case bar
case baz
// I want to use an enum as a dictionary key, so it needs to be Hashable,
// will hardcoding hashValues like this lead to a disaster? What's a better alternative?
public var hashValue: Int {
switch self {
case .foo(let str): return str.hashValue
case .bar: return 0
case .baz: return 1
}
}
// Required for Equatable protocol
public static func ==(lhs: FooBar, rhs: FooBar) -> Bool {
switch (lhs, rhs) {
case (.bar, .bar): return true
case (.baz, .baz): return true
case (.foo(let lhsStr), .foo(let rhsStr)): return lhsStr == rhsStr
default: return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment