Swift Tutorial · Closures, Generics and Errors · Lesson 20 of 30

Swift Generics

Write reusable functions and types with generic parameters, constraints and where clauses.

Create a free account to save this page, take notes and track your progress. Sign in

Generic functions and types

<T> introduces a type parameter. Constraints such as <T: Comparable> say what the type must support. The standard library's Array, Dictionary and Optional are all generic.

Generic types and constraints
struct Stack<Element> {
    private var items: [Element] = []
    mutating func push(_ item: Element) { items.append(item) }
    mutating func pop() -> Element? { items.popLast() }
    var count: Int { items.count }
}

func largest<T: Comparable>(_ items: [T]) -> T? { items.max() }

var stack = Stack<String>()
stack.push("a")
stack.push("b")
print(stack.pop() ?? "-", stack.count)
print(largest([3, 9, 4]) ?? 0)
print(largest(["pear", "apple"]) ?? "")

Output

b 1
9
pear

Run this on your computer — see “Get Started” for setup.

where clauses

A where clause adds more constraints, for example on a collection's element type.

where clauses and constrained extensions
func total<C: Collection>(_ values: C) -> Double where C.Element == Double {
    values.reduce(0, +)
}

extension Array where Element: Numeric {
    func sum() -> Element { reduce(0, +) }
}

print(total([1.5, 2.5, 3.0]))
print(total(Set([2.0, 4.0])))
print([1, 2, 3, 4].sum())

Output

7.0
6.0
10

Run this on your computer — see “Get Started” for setup.

Test yourself

What does <T: Comparable> mean?

  1. T must be an Int
  2. T can be any type that conforms to Comparable
  3. T is optional
  4. T is a class
Show answer

Answer: T can be any type that conforms to Comparable

Was this page helpful?