Created
May 31, 2017 13:13
-
-
Save Frizlab/1a8d8d38304c4fb4d986f60e3b5e8629 to your computer and use it in GitHub Desktop.
A Simple AnyHashable Implementation
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
protocol HashableBox { | |
func unbox<T : Hashable>() -> T? | |
var hashValue: Int {get} | |
func isEqual(_ other: HashableBox) -> Bool | |
} | |
struct ConcreteHashableBox<Base : Hashable> : HashableBox { | |
let originalValue: Base | |
func unbox<T : Hashable>() -> T? { | |
return originalValue as? T | |
} | |
var hashValue: Int { | |
return originalValue.hashValue | |
} | |
func isEqual(_ other: HashableBox) -> Bool { | |
guard let otherAsBase: Base = other.unbox() else {return false} | |
return otherAsBase == originalValue | |
} | |
} | |
struct MyAnyHashable : Hashable { | |
let box: HashableBox | |
init<T : Hashable>(_ object: T) { | |
box = ConcreteHashableBox(originalValue: object) | |
} | |
var hashValue: Int { | |
return box.hashValue | |
} | |
static func ==(_ lhs: MyAnyHashable, _ rhs: MyAnyHashable) -> Bool { | |
return lhs.box.isEqual(rhs.box) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment