0Pricing
Swift Academy · Lesson

Type Parameter Constraints

Require conformance on generic parameters.

Type Parameter Constraints is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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"))

Why Constraints Are Needed

Without Comparable, the compiler rejects a > b because not every type supports it. The constraint is the promise that makes the operation legal.

func minOf<T: Comparable>(_ list: [T]) -> T? {
    list.min()
}
print(minOf([4, 2, 8])!)

The Equatable Constraint

Equatable enables == and !=. Use it to count or find matching elements.

func count<T: Equatable>(_ x: T, in list: [T]) -> Int {
    list.filter { $0 == x }.count
}
print(count(2, in: [2, 3, 2, 2]))

The Hashable Constraint

Hashable lets you use values as Set members or dictionary keys.

func unique<T: Hashable>(_ list: [T]) -> [T] {
    Array(Set(list))
}
print(unique([1, 1, 2, 3, 3]).sorted())

Protocol Constraints

Any protocol can be a constraint. Here a custom protocol unlocks its method on the generic parameter.

protocol Speaker { func speak() -> String }
struct Dog: Speaker { func speak() -> String { "Woof" } }

func announce<T: Speaker>(_ x: T) {
    print(x.speak())
}
announce(Dog())

Class Constraints

You can require T to inherit from a particular class, gaining access to that class's members.

class Animal { func name() -> String { "animal" } }
class Cat: Animal { override func name() -> String { "cat" } }

func describe<T: Animal>(_ x: T) { print(x.name()) }
describe(Cat())

Multiple Constraints

Combine constraints with & to require several protocols at once.

func show<T: CustomStringConvertible & Equatable>(_ a: T, _ b: T) {
    print(a.description, a == b)
}
show(5, 5)

Multiple Type Parameters

A function can have several constrained parameters, each with its own requirements.

func zipMap<K: Hashable, V>(_ keys: [K], _ vals: [V]) -> [K: V] {
    var d: [K: V] = [:]
    for (k, v) in zip(keys, vals) { d[k] = v }
    return d
}
print(zipMap(["a", "b"], [1, 2]))

Constraints on Types

Generic types (not just functions) take constraints too. A generic struct can require its parameter conform to a protocol.

struct SortedBox<T: Comparable> {
    var items: [T]
    var smallest: T? { items.min() }
}
print(SortedBox(items: [5, 1, 9]).smallest!)

Numeric Constraints

Standard protocols like Numeric let generic code do arithmetic across Int, Double, and more.

func sum<T: Numeric>(_ list: [T]) -> T {
    list.reduce(0, +)
}
print(sum([1, 2, 3]))
print(sum([1.5, 2.5]))

Quick Check

Test your understanding of type parameter constraints.

Recap

Type parameter constraints (<T: Protocol> or <T: SomeClass>) tell the compiler what a generic type can do. You saw Comparable, Equatable, Hashable, Numeric, custom protocols, class constraints, multiple constraints with &, and constraints on generic types.

Frequently asked questions

Is the “Type Parameter Constraints” lesson free?

Yes — the full text of “Type Parameter Constraints” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type Parameter Constraints”?

Require conformance on generic parameters. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type Parameter Constraints” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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