I often find myself wanting to store a type-erased Equatable value that does not conform to Hashable. We have AnyHashable, but I was surprised to learn that we don't have an equivalent AnyEquatable type. I've added this to my personal toolkit, but I think it could make a nice addition to the standard library.
struct AnyEquatable {
let base: Any
private let comparitor: (Any) -> Bool
init<E>(_ base: E) where E : Equatable {
self.base = base
self.comparitor = { ($0 as? E) == base }
}
}
extension AnyEquatable: Equatable {
static func == (lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
return lhs.comparitor(rhs.base) && rhs.comparitor(lhs.base)
}
}
We should add the CustomDebugStringConvertible, CustomReflectable, and CustomStringConvertible conformances too, but I've omitted them for brevity.