Type Erasure
It's parameters all the way down
Update: You can read even more about type erasure with lots of example code
A friend of mine @purpleyay gave a talk at try! Swift in Japan about type erasure this week last month. For those of us who didn't attend, what's the deal with type erasure anyway?
More specifically, what is type erasure in the context of Swift and Protocols with associated types? If I could boil it down to one sentence:
Passing a generic type parameter to a protocol's associated type member.
We pass value parameters to functions. A function is usually meaningless without them. So how do we pass a type parameter?
All computing is meaningless in some sense. A computer is just a dumb machine that follows meaningless rules to perform meaningless operations on meaningless values, coming to some meaningless conclusion (or not as the halting case may be).
A protocol like SequenceType
is just floating out there in space. The compiler has no idea what kind of Element
it might contain. That's why you can't declare var x: SequenceType
. How would the compiler know the shape of Element
, Generator
, or Index
?
Only when a specific concrete type like Array
adopts SequenceType
does the compiler have enough information. That locks you in to Array
though. You're using a specific type.
What if you want a way to abstract over all SequenceType
s? That's exactly what AnySequence<T>
does. We passed an explicit type parameter to AnySequence<T>
, which becomes the type member (associated type) to fulfill SequenceType.Element
. That gives the compiler enough concrete information to work with.
You can take that one step further by inheriting from AnySequence<T>
and giving a specific T
: AnyIntSequence: AnySequence<Int>
. At that point you've fully erased both the generic type parameter and the generic type members of the protocol, plus erased the specific implementation details of exactly what kind of sequence you stuffed in at the beginning. Hence calling it type erasure.
You can find more information on associated types in an older post; specifically why Swift doesn't have Protocol<T>
and what the point of associated types is anyway.
This blog represents my own personal opinion and is not endorsed by my employer.