Is it possible to automate the making of type erasure?

Also, as I recently discovered, it is not possible to implement AnyHashable (or AnyEquatable) in pure Swift.

If a class Super implements Equatable, and then it has two different sub-classes Sub1 and Sub2, then there is no way to implement the == operator for AnyEquatable correctly in pure Swift.

Instances s1: Sub1 and s2: Sub2 which compare equal via Super.== still need to compare equal as AnyEquatable(s1) and AnyEquatable(s2), but neither Sub1 nor Sub2 can be converted to each other, and there’s no way to find their common ancestor class which conforms to Equatable and implements ==.

The standard library type AnyHashable is written partially in C++ specifically so that it can find that common ancestor implementing Equatable.

7 Likes