Swift: Attempting to Understand Type Erasure

At the try! Swift Conference in Tokyo, @purpleyay gave a mind-blowing talk on Type Erasure (full video and slides here). I’m honestly still trying to wrap my head around it, and especially the use-cases, but for now, I wanted to write down the example from the talk to keep in my mind and refer to later when it suddenly fits the problem I’m solving.

The Problem

Let’s say you have a simple Pokemon protocol and implementations as follows:

It’s all fun and games, until you want to do a little abstraction. Let’s say you don’t care about what type of Pokemon is doing the attack.

This is a super common scenario, but unfortunately, protocols with associated types do not allow this 😭
Pikachu

The Solution

This is where Type Erasure comes in. After all, we want to erase the explicit Pikachu type, and use the abstract Pokemon type:

Updated Solution

As commenter @salabaha pointed out below, there is an even simpler way to do Type Erasure that works without having to explicitly set the type of the associated type!

Love this!

Update: Unfortunately, this is not Type Erasure – it’s the same as the original solution of having a specific Pokemon in the first place:

And we still cannot make an array of Pokemons with the same power:

Still getting the hang of this 🙈

Conclusion

This still feels like an overly complex fix for something that should just work and hopefully it will in the future. For now, this is a super good pattern to know when working with protocols with associated types.

Oh, and as @allonsykraken points out, one example of where this is used is in Swift’s AnySequence implementation.

Enjoy your new Type Erasure power 💪

Join me for a Swift Community Celebration 🎉 in New York City on September 1st and 2nd. Use code NATASHATHEROBOT to get $100 off!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.