Created
October 24, 2016 19:14
-
-
Save mathewsanders/053ed75e97823bf69ce9ee08d707ec9c to your computer and use it in GitHub Desktop.
Hashable enum
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
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