Swift Type-Erased Protocol Property
Because
_AnyFancyBoxBase
adoptsFancyProtocol
it automatically gains an abstract type member the same way it gains a property or function. It can’t stay abstract though, we need to bind it to something, either a specific type or a generic type parameter.[…]
Now we can define a subclass of the base box; it inherits the protocol conformance and we provide trampoline functions that forward everything to the instance in
var base: Base
.[…]
This type’s raison d’être is in the very first line where we link
Base.Thing
(the associated type we got from the protocol) toAnyFancyBoxBase.T
(the generic parameter on our base class).[…]
Now we can create our type erasing wrapper. The type it is erasing is the concrete type that adopted
FancyProtocol
in the first place.[…]
If we tried to pull this trick with one less type we would end up adding a generic parameter somewhere.