I'm trying to figure out how Swift generics work. Specifically, I didn't manage to find a precise statement about the compilation model. In C++, generics (templates) are not separately compiled as they are instantiated (at least in principle) for each call site. Java generics, instead, are separately compiled. What is the case with Swift, concerning separate compilation of generics?
Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
Swift 4s 'Arrays' and 'Dictionary' types belong to generic collections. With the help of arrays and dictionaries the arrays are defined to hold 'Int' values and 'String' values or any other types.
It's a combination of the two, depending on what the optimizer decides will get better performance. They talk about it near the end of WWDC Session 404: Advanced Swift. The slide says:
Swift can run generic code directly
Optimizer can produce specialized versions of generic code at will
- Separate compilation of generics
- Faster compiles
- Flexibility to trade code size for speed
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