Wednesday, October 12, 2016

Swift Type-Erased Protocol Property

Russ Bishop:

Because _AnyFancyBoxBase adopts FancyProtocol 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) to AnyFancyBoxBase.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.

Comments RSS · Twitter

Leave a Comment