The type erasure pattern – a summary

As we've seen in this section, the type erasure pattern helps to use protocols with associated types when the implementation as generic constraints isn't desired. By following this pattern, you'll be able to move from the world of protocols to the world of concrete types with generics.

There are at least two common ways to implement the type erasure pattern. The first implementation lets you get away with simple protocols that are defined simply in terms of functions. As soon as one stored property is required by the protocol, you'll need to implement the fully fledged pattern, with the boxing and abstract classes.

In both cases, you'll need to implement the public wrapper class, so start with that.

In the case of simple protocols that expose only functions, you can benefit from powerful Swift functions and store the wrapped object's functions directly. Otherwise, you'll need to implement the boxing and abstract classes:

If you have played with Sourcery before, it is also possible to implement the type erasure patterns as a Sourcery stencil in order to reduce the boilerplate. Olivier Halligon maintains a repository of Sourcery stencils (https://github.com/AliSoftware/SourceryTemplates/blob/master/Templates/TypeErase.stencil) where you can find an implementation of it.