TExcelTAD
Home › Swift › Swift Generics

Swift Generics

Generics let you write a function or type once and use it with many types, while keeping full type safety. You have been using generics all along: Array<Element>, Dictionary<Key, Value> and Optional<Wrapped> are generic types, which is why one Array implementation works for [Int], [String] and [Book].

The problem generics solve

Without generics you would need a separate function for every type:

swift
func swapInts(_ a: inout Int, _ b: inout Int) { (a, b) = (b, a) }
func swapStrings(_ a: inout String, _ b: inout String) { (a, b) = (b, a) }
// …and one more for every other type

Generic functions

A generic function declares one or more type parameters in angle brackets. T is a placeholder that is replaced by a real type at each call:

swift · try it yourself
func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 1, y = 2
swapValues(&x, &y)
print(x, y)

var first = "left", second = "right"
swapValues(&first, &second)
print(first, second)

func pair<A, B>(_ a: A, _ b: B) -> String {
    "(\(a), \(b))"
}
print(pair(42, true))
2 1
right left
(42, true)

Swift infers T from the arguments. Both arguments of swapValues must have the same T, so swapValues(&x, &first) would not compile.

Type constraints

Often you need to do something with a T — compare it, add it, print it. A constraint limits T to types that conform to a protocol:

swift · try it yourself
func largest<T: Comparable>(_ items: [T]) -> T? {
    guard var best = items.first else { return nil }
    for item in items where item > best {
        best = item
    }
    return best
}

print(largest([3, 9, 4]) ?? 0)
print(largest(["pear", "apple", "zucchini"]) ?? "")
print(largest([Double]()) == nil)
9
zucchini
true

Without T: Comparable, the > operator would be a compile error, because not every type can be compared.

Several constraints can be listed in a where clause:

swift
func summary<T>(_ values: [T]) -> String where T: Numeric, T: CustomStringConvertible { … }

Generic types

You can make your own generic structs, classes and enums. Here is a simple stack (last in, first out):

swift · try it yourself
struct Stack<Element> {
    private var items: [Element] = []

    var isEmpty: Bool { items.isEmpty }
    var top: Element? { items.last }

    mutating func push(_ item: Element) {
        items.append(item)
    }

    mutating func pop() -> Element? {
        items.popLast()
    }
}

var history = Stack<String>()
history.push("home")
history.push("profile")
history.push("settings")

print("Top:", history.top ?? "none")
while let page = history.pop() {
    print("back from", page)
}
print("Empty:", history.isEmpty)

var numbers = Stack<Int>()     // the same code, another type
numbers.push(7)
print(numbers.top ?? 0)
Top: settings
back from settings
back from profile
back from home
Empty: true
7

Extending generic types

An extension can use the type parameter, and a constrained extension can add members only for certain element types:

swift · try it yourself
struct Box<Value> {
    let value: Value
}

extension Box {
    func map<New>(_ transform: (Value) -> New) -> Box<New> {
        Box<New>(value: transform(value))
    }
}

extension Box where Value == String {
    var shouted: String { value.uppercased() }
}

let price = Box(value: 20)
let label = price.map { "Price: \($0) USD" }
print(label.value)
print(label.shouted)
Price: 20 USD
PRICE: 20 USD

shouted exists only on Box<String> — calling it on Box<Int> is a compile error.

Protocols with associated types

Protocols use associated types instead of angle brackets. The adopting type decides what the associated type is:

swift · try it yourself
protocol Container {
    associatedtype Item
    var count: Int { get }
    mutating func add(_ item: Item)
}

struct Basket: Container {
    var fruits: [String] = []         // Item is inferred as String
    var count: Int { fruits.count }
    mutating func add(_ item: String) { fruits.append(item) }
}

var basket = Basket()
basket.add("lychee")
basket.add("rambutan")
print(basket.count, basket.fruits)
2 ["lychee", "rambutan"]

Generic vocabulary

Syntax Meaning
func f<T>(_ x: T) Generic function with type parameter T
<T: Equatable> T must conform to Equatable
where T: Hashable, U == Int Extra constraints or same-type requirements
struct Stack<Element> Generic type
associatedtype Item Placeholder type inside a protocol
some Collection Opaque type: one specific conforming type

Tip: Name type parameters descriptively when it helps (Element, Key, Value). Single letters like T and U are fine for short, general functions.

Test yourself

What does <T: Comparable> mean in a function declaration?

  1. T must be an Int
  2. T can be any type that conforms to Comparable
  3. T is optional
  4. The function returns a Comparable

Which of these is a generic type from the standard library?

  1. Int
  2. Bool
  3. Array<Element>
  4. String

How does a protocol declare a placeholder type?

  1. protocol P<T>
  2. associatedtype Item
  3. typealias T
  4. generic Item