0Pricing
Swift Academy · Lesson

Type Parameter Constraints

Require conformance on generic parameters.

Generics Recap

A generic function uses a type parameter like <T> so it works with many types. But unconstrained T can only be passed around, not inspected. Constraints unlock capabilities.

func identity<T>(_ x: T) -> T { x }
print(identity(5))
print(identity("hi"))

The Comparable Constraint

Writing <T: Comparable> guarantees values of T support <, >, and friends, so you can compare them.

func largest<T: Comparable>(_ a: T, _ b: T) -> T {
    a > b ? a : b
}
print(largest(3, 9))
print(largest("apple", "pear"))

All lessons in this course

  1. Type Parameter Constraints
  2. where Clauses on Functions
  3. Constraining Associated Types
  4. Generic Subscripts and Extensions
← Back to Swift Academy