Generics: a robust overloading framework for creating a set of functions that can work with any type.


struct Stack<T> {
     var elements = T[]()

Generics build on the earlier, but less ideal ways of handling the case where the same function needs to work with multiple types. Originally, a separate method would need to be defined for every type to be handled (e.g. String, Int, Float, Array, etc). This was improved upon with the invention of overloading. That still required separate methods to be defined, but at runtime, the correct one would be called based on the type passed in as a parameter.

Swift also supports the "Any" protocol, which only requires one method to be defined and called. But it has the drawback that an "Any" object loses it's type information, so it won't respond to any of the type specific methods that might be defined. Generics are very similar to the "Any" approach, as only one method needs to be defined and called, but it preserves the type information, which is good for safety and performance.

Generic types are everywhere: Array<T> and Dictionary<K,V> are generic structs. Optional<T> is a generic enum. Generic classes are possible too. Swift can directly run generic code, and the optimizer can produce specialized versions of generic code on demand. Since generics are compiled seprately, this leads to faster compiles, and the flexibility to trade code size for speed.

struct Stack<T> {
  mutating func push(x: T) {
    items += x
  mutating func pop() -> T {
    return items.removeLast()
  var items: T[]

var intStack = Stack<Int>()
var imageStack = Stack<UIImage>()