0Pricing
Swift Academy · Lesson

Constraints (where), type inference

Constrain generic code using where (e.g., Equatable/Comparable or Element constraints) and see how Swift infers generic types at call sites.

Constraints (where), type inference is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. 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 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why constraints?

Add constraints so generic code uses certain operations (like == or <). Swift's type inference then picks concrete types at calls.

Equatable constraint

where T: Equatable permits equality checks. Without it, == is not available for any T.

// Find the first index of value in an array of T
func indexOf<T>(_ value: T, in array: [T]) -> Int? where T: Equatable {
    for (i, x) in array.enumerated() {
        if x == value { return i }        // allowed because T: Equatable
    }
    return nil
}
print(indexOf(3, in: [1,2,3,2]) ?? -1)     // 2
print(indexOf("b", in: ["a","b","c"]) ?? -1)  // 1

Comparable constraint

Using a constraint like T: Comparable enables ordering operations such as <.

// Return the minimum value of a collection when elements are Comparable
func minimum<T: Comparable>(_ xs: [T]) -> T? {
    guard var best = xs.first else { return nil }
    for x in xs.dropFirst() {
        if x < best { best = x }
    }
    return best
}
print(minimum([7,3,9]) ?? -1)    // 3
print(minimum(["b","a","c"]) ?? "?") // "a"

Extension with where

Use where Element: ... to add APIs only for certain element types (here, arrays of Equatable).

// Add a helper only when the array's Element is Equatable
extension Array where Element: Equatable {
    func removingDuplicates() -> [Element] {
        var seen: [Element] = []
        for x in self {
            if !seen.contains(x) { seen.append(x) }
        }
        return seen
    }
}
print([1,2,2,3].removingDuplicates())   // [1,2,3]

Multiple constraints

Combine constraints: constrain the generic type and its associated types (e.g., S.Element: Equatable).

// Require both Sequence and Equatable elements; force same-type relationship
func allEqual<S>(_ s: S) -> Bool
where S: Sequence, S.Element: Equatable {
    var it = s.makeIterator()
    guard let first = it.next() else { return true }
    while let v = it.next() { if v != first { return false } }
    return true
}
print(allEqual([2,2,2]))   // true
print(allEqual([1,2,1]))   // false

Inference in practice

Swift infers generic parameters from arguments and context, so you rarely specify <T> explicitly.

// Inference: compiler deduces concrete types
let i = indexOf(10, in: [5,10,15])   // T is Int
let j = minimum(["z","x"])           // T is String
print(i ?? -1, j ?? "")

Meaning of where

Quick check: What does a where clause do?

Recap

Recap: Constrain generics with where (e.g., T: Equatable, Element: Comparable) and rely on Swift's type inference to pick concrete types at calls.

Frequently asked questions

Is the “Constraints (where), type inference” lesson free?

Yes — the full text of “Constraints (where), type inference” is free to read here on the web, and the Swift Academy course includes 3 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 “Constraints (where), type inference”?

Constrain generic code using where (e.g., Equatable/Comparable or Element constraints) and see how Swift infers generic types at call sites. 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 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Constraints (where), type inference” 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. Generic functions & types
  2. Constraints (where), type inference
  3. Generic algorithms on collections
← Back to Swift Academy