Skip to content

Instantly share code, notes, and snippets.

@Frizlab
Created May 31, 2017 13:13
Show Gist options
  • Save Frizlab/1a8d8d38304c4fb4d986f60e3b5e8629 to your computer and use it in GitHub Desktop.
Save Frizlab/1a8d8d38304c4fb4d986f60e3b5e8629 to your computer and use it in GitHub Desktop.
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