Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Created April 12, 2024 10:18
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 T1T4N/626cb2919ce8549a47fe045419b7e5e6 to your computer and use it in GitHub Desktop.
Save T1T4N/626cb2919ce8549a47fe045419b7e5e6 to your computer and use it in GitHub Desktop.
A custom simple AnyHashable implementation
protocol HashableBox: Hashable {
func `as`<T : Hashable>(_: T.Type) -> T?
func isEqual(_ other: any HashableBox) -> Bool
}
struct ConcreteHashableBox<Base: Hashable>: HashableBox {
let base: Base
func `as`<T>(_: T.Type) -> T? where T : Hashable {
return base as? T
}
func hash(into hasher: inout Hasher) {
hasher.combine(base)
}
func isEqual(_ other: any HashableBox) -> Bool {
guard let otherAsBase = other.as(Base.self) else { return false }
return otherAsBase == base
}
}
struct MyAnyHashable: Hashable {
let box: any HashableBox
init<T : Hashable>(_ object: T) {
box = ConcreteHashableBox(base: object)
}
func hash(into hasher: inout Hasher) {
box.hash(into: &hasher)
}
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