Created
April 12, 2024 10:18
-
-
Save T1T4N/626cb2919ce8549a47fe045419b7e5e6 to your computer and use it in GitHub Desktop.
A custom 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: 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