There are three ways to implement generics:
Just a tool for compile time checks, but every template instance is compiled to the same byte/assembly code implementation (Java, as noted in comments "type erasure" implementation)
Each template instantiation is compiled to specialized code (C++, C#)
Combination of #1 and #2
Which one is implemented in Swift?
Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example, List<Integer> will be converted to the non-generic type List , which ordinarily contains arbitrary objects.
Some generics stay in the compiled class -- specifically including method signatures and class definitions, for example. At runtime, no objects keep their full generic type, but even at runtime you can look up the generic definition of a class or a method.
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
Swift starts by compiling a single implementation that does dynamic type checking, but the optimizer can then choose to clone off specialized implementations for particular types when the speed vs code size tradeoffs make sense. Ideally, this gets 90% of the speedup of always cloning, without the code size and compilation time exploding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With