skip to content

In a Swift generic declaration, what can a `where` clause express that a constraint in the angle brackets cannot, such as a same-type requirement?

level: middleimportance: should knowfreq 50%

answer

  1. sugar for the simple case
  2. requirements on associated types
  3. two types must be identical
  4. tuple labels count
  5. non-generic placeholder diagnostic

basics

~20 s

Angle brackets give each placeholder a single bound: a protocol, composition or superclass. A where clause can also constrain associated types (S.Element: Hashable) and state same-type requirements like S.Element == Key, enforced as exact type identity.

solid answer

~50 s

`<T: Comparable>` and `<T> where T: Comparable` mean the same thing: the angle brackets are the short form for the simple case. You need a `where` clause in two situations. One is when the requirement is on something other than a declared placeholder, such as `S.Element: Hashable`. The other is when it relates two types with `==`. In a generic `Cache<Key: Hashable, Value>`, `func values<S: Sequence>(for keys: S) -> [Value] where S.Element == Key` accepts an array, a `Set` or any other sequence, as long as it yields exactly `Key`. "Exactly" is literal. A method that requires `S.Element == (Key, Value)` rejects a `Dictionary`, because a dictionary's element is the labeled tuple `(key: Key, value: Value)`. A same-type requirement that pins the function's own placeholder, as in `where T == Int`, makes it non-generic: Swift 5 mode warns and Swift 6 mode reports an error.

code

swift · 23 lines
swift
struct Cache<Key: Hashable, Value> {
    private var storage: [Key: Value] = [:]

    subscript(key: Key) -> Value? {
        get { storage[key] }
        set { storage[key] = newValue }
    }

    // Same-type requirement: the sequence must yield exactly (Key, Value) pairs.
    mutating func insert<S: Sequence>(contentsOf pairs: S) where S.Element == (Key, Value) {
        for (key, value) in pairs { storage[key] = value }
    }

    // Same-type plus conformance: the keys come from any sequence of Key.
    func values<S: Sequence>(for keys: S) -> [Value] where S.Element == Key {
        keys.compactMap { storage[$0] }
    }
}

var prices = Cache<String, Double>()
prices.insert(contentsOf: [("tea", 3.5), ("cake", 4.0)])
prices.insert(contentsOf: zip(["juice"], [2.5]))     // Zip2Sequence yields unlabeled (String, Double)
print(prices.values(for: Set(["tea", "juice"])).sorted())

go deeper

for a junior

Recall that a where clause sits before the opening brace and that <T: P> and <T> where T: P mean the same thing.

for a middle

Explain the two jobs only a where clause does: constraining associated types such as S.Element, and relating two types with ==.

for a senior

Show that same-type means identical, including tuple labels, and that pinning a function's own placeholder to a concrete type warns in Swift 5 mode and fails in Swift 6 mode.

for a principal

Coach reviewers to read each requirement as API surface: a requirement that is too strict locks out callers, and one that is too loose pushes casts into the body.

## Two spellings of one requirement A generic declaration can state requirements in two places: - **In the angle brackets**: `func f<T: Comparable>(_ x: T)`. After the colon comes exactly one class, protocol or protocol composition, and it applies to the placeholder just declared. - **In a generic `where` clause**: `func f<T>(_ x: T) where T: Comparable`. The clause goes right before the opening brace and lists comma-separated requirements. For a simple bound the two forms are **identical in meaning**: the language reference states that `<T: Comparable>` is equivalent to `<T> where T: Comparable`. The `where` clause exists for requirements the short form cannot express. ## What only a `where` clause can say | Requirement | Example | Meaning | |---|---|---| | conformance on an associated type | `where S.Element: Hashable` | each element is hashable | | same-type between two types | `where S1.Element == S2.Element` | both sequences yield one type | | same-type to a type in scope | `where S.Element == Key` | the sequence yields the cache's key type | | several at once | `where S.Element == Key, Value: Equatable` | all must hold | `<S: Sequence, S.Element: Equatable>` is a parse error ("expected '>' to complete generic parameter list"), and so is `<T == Int>`. Those requirements only fit in a `where` clause. (Constraining an `associatedtype` inside a protocol declaration uses a `where` clause too. That case belongs with the material on associated types.) ## Same-type requirements in a generic cache ```swift struct Cache<Key: Hashable, Value> { private var storage: [Key: Value] = [:] func values<S: Sequence>(for keys: S) -> [Value] where S.Element == Key { keys.compactMap { storage[$0] } } } ``` `Key: Hashable` sits in the angle brackets because the cache stores a `[Key: Value]`, and `Dictionary` itself declares `Key: Hashable`. Without that bound, the stored property fails with "type 'Key' does not conform to protocol 'Hashable'". The method adds its own placeholder `S` and ties it to the type's `Key` with `==`. Callers may pass `["tea", "cake"]`, `Set(["tea"])` or a lazy filtered sequence. Passing `[1, 2]` to a `Cache<String, Int>` fails to compile, because the requirement fixes the element type to `String`. ## Same-type means identical A **same-type requirement** (`==`) asks for type identity. It does not ask for convertibility or a similar shape. The sharpest consequence involves tuples: 1. `mutating func insert<S: Sequence>(contentsOf pairs: S) where S.Element == (Key, Value)` accepts `[("tea", 3.5)]` and `zip(keys, values)`, because both yield the unlabeled tuple `(String, Double)`. 2. It rejects `["juice": 2.5]`. A `Dictionary`'s `Element` is `(key: Key, value: Value)`, and Swift reports "requires the types 'Dictionary<String, Double>.Element' (aka '(key: String, value: Double)') and '(String, Double)' be equivalent". 3. To fix it, convert at the call with `dict.map { ($0.key, $0.value) }`, or add an overload whose requirement names the labeled tuple, `where S.Element == (key: Key, value: Value)`. ## When a same-type requirement backfires A `where` clause can also pin a placeholder to a concrete type, and that is sometimes a mistake: - On a function's **own** placeholder, `func g<T>(_ x: T) where T == Int` makes `T` pointless. Swift reports "same-type requirement makes generic parameter 'T' non-generic". In Swift 5 language mode that is a warning ("this is an error in the Swift 6 language mode"), and in Swift 6 language mode it is an error. Write `func g(_ x: Int)`. - On a placeholder from the **enclosing** context, the same requirement is useful. `extension Cache where Key == String`, or a member's own `where Key == String`, adds API only for string-keyed caches. - Two contradictory requirements, such as `Element == Int` together with `Element: SomeProtocol` that `Int` does not adopt, are rejected because no type can satisfy both. ## How to read a `where` clause in review - Every requirement is checked at the **call site at compile time**. Nothing is checked at run time. - Inside the body, each requirement becomes a fact the type checker uses. After `S.Element == Key`, a `storage[$0]` lookup compiles without a cast. - Prefer the weakest requirement that makes the body compile. `S: Sequence` with `S.Element == Key` serves more callers than `[Key]`.

  • How do you let that `insert(contentsOf:)` accept a `Dictionary` as well?
    You can convert at the call with `cache.insert(contentsOf: dict.map { ($0.key, $0.value) })`. Or you can add an overload whose requirement names the labeled tuple, `where S.Element == (key: Key, value: Value)`. Both overloads can coexist: an array of unlabeled pairs picks the first and a dictionary picks the second, because each matches only one requirement exactly.
  • Can a subscript declare its own placeholders and `where` clause?
    Yes. Subscripts can be generic: `subscript<S: Sequence>(keys keys: S) -> [Value] where S.Element == Key` lets `cache[keys: ["tea", "cake"]]` return several values at once. Subscript parameters have no argument label by default, so the label must be spelled out (`keys keys`) if callers should write `keys:`.

  • A where clause works only on extensions, so a function needs the angle brackets.
  • S.Element == Key accepts any element type that converts to Key.
  • A labeled tuple and an unlabeled tuple satisfy the same same-type requirement.
  • Writing <T == Int> in the angle brackets pins T to Int.
  • where T == Int on a function's own placeholder is a harmless way to restrict it.

Assumes Swift 6.4: a same-type requirement that makes a function's own generic parameter non-generic is a warning in Swift 5 language mode and an error in Swift 6 language mode.