skip to content

In Swift, how does a generic function like `largest(in:)` infer `T` at the call site, and why must it constrain `T` to `Comparable`?

level: juniorimportance: must knowfreq 70%

answer

  1. placeholder fixed once per call
  2. read from the argument types
  3. body sees only the declared constraint
  4. binary operator cannot be applied
  5. no angle brackets at the call

basics

~20 s

Swift fixes T at each call from the argument types, so [Int] makes T Int. The body may use only what the constraints promise, so value > best compiles only after T: Comparable is declared.

solid answer

~40 s

A generic function declares a placeholder in angle brackets: `func largest<T: Comparable>(in values: [T]) -> T?`. At each call the type checker infers `T` from the arguments, so `largest(in: [72, 95])` binds `T` to `Int` and `largest(in: names)` binds it to `String`. You never write `largest<Int>(in:)`, because Swift does not let you explicitly specialize a function: Swift 5 mode warns and Swift 6 mode makes it an error. The body is checked once against the declaration, not against each caller. With a bare `T`, the comparison fails with "binary operator '>' cannot be applied to two 'T' operands". Adding `: Comparable` makes `<` and `>` available in the body, and it makes every caller prove the conformance. Passing a plain struct fails at the call with "requires that 'Point' conform to 'Comparable'".

code

swift · 14 lines
swift
func largest<T: Comparable>(in values: [T]) -> T? {
    guard var best = values.first else { return nil }
    for value in values.dropFirst() where value > best {
        best = value
    }
    return best
}

let scores = [72, 95, 88]
let names = ["pear", "fig", "quince"]

print(largest(in: scores) ?? -1)      // 95: T inferred as Int
print(largest(in: names) ?? "none")   // quince: T inferred as String
print(largest(in: [Int]()) ?? -1)     // -1: the typed empty array fixes T as Int

go deeper

for a junior

Recall the syntax: angle brackets declare T, a colon adds a protocol constraint, and callers never name T because Swift infers it from the arguments.

for a middle

Explain that the body is checked once against the signature, so the constraint decides which operators compile, and that the caller's conformance is proved at compile time.

for a senior

Show inference edge cases: an empty literal falls back to [Any], mixed literals are typed [Double], and explicit specialization of a function warns in Swift 5 mode and is an error in Swift 6 mode.

for a principal

Coach reviewers to ask for the weakest constraint the body actually needs, because each extra protocol narrows every future caller of a shared helper.

## What a generic function declares A **generic function** is written once and works with many types. Its **type parameters** (placeholders) are listed in angle brackets after the name: ```swift func largest<T: Comparable>(in values: [T]) -> T? { guard var best = values.first else { return nil } for value in values.dropFirst() where value > best { best = value } return best } ``` `T` is a placeholder for one concrete type, and `: Comparable` is a **type constraint**. A constraint says what any type substituted for `T` must provide. The constraint after the colon can be a protocol, a protocol composition, or a superclass. Every use of `T` inside the declaration (the parameter `[T]`, the return type `T?`, the local `best`) means the same type within one call. ## How Swift infers `T` at the call site You never name `T` when you call the function. The type checker solves for it from the arguments: - `largest(in: [72, 95, 88])` binds `T` to `Int`, because the array literal is `[Int]`. - `largest(in: ["pear", "fig"])` binds `T` to `String`. - `largest(in: [3, 2.5])` binds `T` to `Double`. The integer literal `3` can also be a `Double`, and the mixed literal is typed `[Double]`. - `largest(in: [])` does **not** compile. An empty literal names no element type, so Swift falls back to `[Any]`, and the compiler reports "type 'Any' cannot conform to 'Comparable'". Write `[] as [Int]` or pass a typed variable. - `largest<Int>(in: scores)` is rejected with "cannot explicitly specialize global function 'largest(in:)'". In Swift 5 language mode this is a warning, and in Swift 6 language mode it is an error. A function's type arguments are always inferred. When inference needs help, annotate the argument or the result instead: `let top: Double? = largest(in: [3, 2.5])`. One call binds `T` to exactly one type. Every element of the array has that type, and the result is that type too, so `largest(in: scores)` returns `Int?` and not `Any?`. ## What the constraint unlocks in the body Swift **type-checks a generic body once**, against its own signature. It does not re-check the body for each caller. Inside the body, `T` is only what its constraints say it is: | Declaration | What the body may do with a `T` value | |---|---| | `<T>` | store it, return it, pass it to other generic code | | `<T: Equatable>` | also compare with `==` and `!=` | | `<T: Comparable>` | also order with `<`, `>`, `<=`, `>=` and call `max()` on `[T]` | | `<T: Hashable>` | also use it as a `Dictionary` key or `Set` element | Remove the constraint and the loop above fails to compile with **"binary operator '>' cannot be applied to two 'T' operands"**. That `T` might turn out to be `Int` at some call does not help: the body must be valid for every type the signature allows. ## What the constraint demands of the caller A constraint is a contract in both directions. The body gains operations, and every call site must supply a type that conforms: 1. `struct Point { var x: Int }` passed as `largest(in: [Point(x: 1)])` fails **at compile time, at the call**, with "global function 'largest(in:)' requires that 'Point' conform to 'Comparable'". 2. Declaring `extension Point: Comparable` and implementing `<` fixes it. Swift synthesizes `Comparable` only for enumerations without a raw value, never for structs. 3. No check happens at run time. A program that compiles has already proved each call's conformance. ## Common traps - Writing `largest<Int>(...)` because generic types accept `Cache<String, Int>()`. Types take explicit arguments, but functions do not. - Expecting the body to "know" the caller's type. Code written only for `Int` belongs in a separate non-generic function. - Constraining too tightly, for example `T: Numeric` when only ordering is needed. That locks out `String` and other `Comparable` types for no gain. - Treating an unconstrained `T` as `Any`. `T` is one fixed type per call, which is why the result keeps its type, while an `Any` value would need a cast to be used.

  • Why does `largest(in: [])` fail to compile, and how do you fix it?
    An empty literal names no element type, so Swift falls back to its default, `[Any]`. That binds `T` to `Any`, and the compiler reports "type 'Any' cannot conform to 'Comparable'". Give the literal a type, as in `largest(in: [] as [Int])` or `largest(in: [Int]())`, or pass a typed variable. Then `T` is read from that type.
  • A generic type takes `Cache<String, Int>()`. Why can't a generic function take `largest<Int>(in:)`?
    Swift lets you write a generic argument clause for a type but not for a function or initializer, whose type arguments are always inferred from the call. `largest<Int>(in:)` is reported as "cannot explicitly specialize global function": Swift 5 mode warns and Swift 6 mode rejects it. To steer inference, annotate the argument (`[] as [Int]`) or the result (`let top: Double? = ...`).

  • You write largest<Int>(in: scores) to choose T at the call site.
  • An unconstrained T can use > because every real caller passes comparable values.
  • Swift type-checks the generic body again for each concrete type it is called with.
  • A single call can bind T to Int for some elements and String for others.
  • A missing Comparable conformance is caught at run time, when > is first reached.

Assumes Swift 6.4: explicitly specializing a generic function, as in largest<Int>(in:), is a warning in Swift 5 language mode and an error in Swift 6 language mode.