Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 146 ยท Functions and Closures

Generic Functions

Learn Swift generic functions - type parameters, protocol constraints, where clauses, why swap and max are generic, specialization and common compiler errors, with runnable examples.

Suppose you write a function that returns the larger of two integers. A week later you need the same thing for two Double values, then for two strings. Copying the function three times with different types is tedious, and every bug fix has to be made three times. Swift's answer is generics: you write the function once, with a placeholder where the type goes, and the compiler produces a correct version for each type you actually use.

You have been using generic code since your first array. [Int] is Array<Int>, and Array works for any element type. This lesson shows how to write generic functions; generic types come in Generics and the protocols that make constraints possible in Protocols.

The problem generics solve

Without generics, a function that swaps two values must commit to a type:

Swift Duplicated code for each type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two bodies are identical; only the types differ. Now make the type a parameter.

Your first generic function

A type parameter is a name in angle brackets after the function name. By convention a single parameter is called T, or a more descriptive name such as Element when it helps. Inside the function you use it like any type.

Swift One swap for every type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

<T> declares the placeholder. Both parameters have type T, so they must be the same type: you cannot swap an Int with a String. Swift infers T from the arguments, so you never write swapValues<Int>(...) yourself (although you could).

The function does not know anything about T, so it can only do things that work for every type: copy it, assign it, pass it around. That restriction is not a weakness. It is the reason generic code is safe: the compiler checks the function body once, not once per type.

Generic functions over collections

Type parameters can appear in any position, including inside other types. The function below takes an array of any element type and returns its last element, or nil if the array is empty. Its return type uses the same placeholder.

Swift Placeholders inside other types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A function can have several type parameters, separated by commas: <A, B>. They may be different types or the same. apply shows how the output type is inferred from the closure, a feature you will see in map itself: Array.map is a generic method with a type parameter for the result.

Why == and < do not work yet

A natural next step is to write a generic function that finds the largest item. Try it:

Swift Comparing unconstrained values (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler refuses with binary operator '>' cannot be applied to two 'T' operands. That is correct: a placeholder could stand for a type that has no ordering, such as a function or a struct without comparison. To use >, you need to promise that T supports it.

Constraints

A constraint limits which types may replace a placeholder. You write it after the parameter name with a colon, naming a protocol (or a class):

Swift Constraining T to Comparable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Comparable provides <, >, <= and >=; Equatable provides == and !=. The standard library has many more, for example Hashable (can be a dictionary key or set member), Numeric (supports +, -, *) and Sequence. The constraint is a contract: the caller can only pass types that fulfil it, and the body can use everything the protocol guarantees.

Swift also has a safety net on the caller's side. If you pass something that does not conform, the error is clear:

Swift A type that does not meet the constraint (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is global function 'largest' requires that 'Point' conform to 'Comparable'. The fix is either to make Point conform (see Equatable, Hashable and Comparable) or to give the function a closure that compares.

Constraints with several protocols

Combine requirements with &, which builds a protocol composition. A generic function that needs to both compare and print its items can use T: Comparable & CustomStringConvertible. The first function below needs arithmetic; the second needs both abilities:

Swift Numeric constraints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice var total: T = 0. That works because Numeric is ExpressibleByIntegerLiteral: a literal 0 can create any Numeric type, whether Int, Double or something else.

where clauses

Sometimes the requirement is not on T itself but on a related type. A where clause after the signature lists extra conditions. For example, a function that takes any sequence and needs its elements to be equatable:

Swift where clauses relate types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

allEqual works for arrays, strings (whose elements are Character), ranges and anything else that is a Sequence. The where S.Element: Equatable line says "whatever this sequence produces must be comparable with ==". haveSameElements uses two conditions: both sequences produce the same element type (== in a where clause means the types are identical), and that type is Hashable.

You can also write simple constraints in the angle brackets and complex ones in where. They are equivalent; use whichever reads better. As a rule, put the single obvious constraint (T: Comparable) in the brackets, and put relationships between types in where.

Generics and closures: a reusable algorithm

Constraints are not the only way to give a generic function new abilities. You can also take a closure as a parameter, which is how sorted(by:) and first(where:) work. This is useful when a type has several valid orderings, or no natural one:

Swift A generic function that takes a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Book is neither Comparable nor Equatable, but the function still works because the caller supplies the comparison. A rule of thumb: use a constraint when the type has one obvious meaning of "bigger", and a closure when the answer depends on the situation.

How the compiler makes generics fast

A common worry is that generics must be slow, because the type is unknown while the function is written. Swift avoids that in two ways. By default, a generic function receives hidden extra information at run time (such as how big T is and how to copy it), so the compiled code can handle any type. When the compiler sees a call like largest([3, 9, 2]) and can see the function body, it often performs specialization: it makes a private copy of the function for Int and optimizes it as if you had written it by hand for integers. With -O, the Int version typically has no generic overhead at all.

The practical advice is simple: write the generic version first. Generic code in the standard library, such as sorted() and map, is as fast as hand-written loops. Only if profiling shows a hot spot across module boundaries do you need to think about @inlinable or @_specialize, both beyond this lesson.

Generic functions are about the type. If you instead want a function that accepts "anything that behaves like X" and keeps the concrete type hidden, you will meet some Protocol and any Protocol in Opaque and Existential Types.

Common mistakes

  • Using one placeholder for unrelated values. func pair<T>(_ a: T, _ b: T) requires both arguments to have the same type. Use <A, B> if they may differ.
  • Forgetting a constraint, then fighting the error. If you need ==, <, + or hash, add Equatable, Comparable, Numeric or Hashable.
  • Over-generalizing. If a function only ever works with Int, a plain function is simpler to read. Make it generic when a second type appears.
  • Using Any instead of a placeholder. [Any] throws away type information, so you must cast later. A generic keeps the exact type: [T] in, T out.
  • Vague names. T, U are fine for tiny functions. Use descriptive names (Element, Key, Value, Input, Output) when there are several or the meaning matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the <T> in func firstOrNil<T>(_ items: [T]) -> T? declare?

    T is a type parameter. Swift infers it from the call, so firstOrNil([1, 2]) uses Int and firstOrNil(["a"]) uses String.
  2. 2. Why does func bigger<T>(_ a: T, _ b: T) -> T { a > b ? a : b } not compile?

    An unconstrained T only supports operations every type has. Writing <T: Comparable> promises the comparison operators exist.
  3. 3. What does where S.Element == Int mean in a generic signature?

    A same-type requirement says two types must be identical. S may be an array, a range or any other sequence whose Element is Int.
  4. 4. Which constraint lets you write var total: T = 0 and total += value?

    Numeric provides the arithmetic operators and allows integer literals, so both the literal 0 and += are valid.
  5. 5. How does the Swift compiler usually avoid the cost of generics for a call like largest([3, 9, 2])?

    Specialization generates a version of the generic function for the concrete type, which the optimizer can inline and tune like hand-written code.

Summary

  • A generic function uses type parameters such as <T> so one definition works for many types; Swift infers the types from each call.
  • Several parameters can share a placeholder (same type) or use different ones (<A, B>).
  • Without constraints you can only copy and pass values around; add T: Comparable, Equatable, Numeric, Hashable and so on to unlock operations.
  • where clauses constrain related types, for example where S.Element: Equatable or A.Element == B.Element.
  • Take a closure parameter when different callers need different behavior, as sorted(by:) does.
  • With optimization, the compiler specializes generic functions for concrete types, so they are normally as fast as hand-written code.
  • Prefer a placeholder over Any: it keeps the exact type and avoids casts.

Next: Recursion