Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Simple AnyHashable Implementation
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
You can’t perform that action at this time.