Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Swift generics separately compiled? [duplicate]

Tags:

generics

swift

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?

like image 858
Gepp Avatar asked Sep 18 '14 16:09

Gepp


People also ask

How do generics work in Swift?

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.

Why would you use generics in Swift?

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.

Which of the following are generic types in Swift?

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.


1 Answers

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
like image 180
Nate Cook Avatar answered Nov 15 '22 08:11

Nate Cook