In Swift, how does `extension Array where Element: Numeric` add a method only some arrays get, and what error does a `[String]` caller see?
answer
- members gated by a requirement
- body may assume the constraint
- referencing instance method requires
- one member, its own where
- generic callers restate it
basics
~20 sA constrained extension declares members that exist only when its where clause holds. [4, 8].total() compiles, while ["tea"].total() fails at compile time with "referencing instance method 'total()' on 'Array' requires that 'String' conform to 'Numeric'".
solid answer
~40 s`extension Array where Element: Numeric { func total() -> Element { reduce(.zero, +) } }` adds `total()` to every array whose element conforms to `Numeric`. Inside the extension the compiler knows `Element: Numeric`, so `.zero` and `+` type-check. For any other element type the member is unavailable, and the call is rejected at compile time with "referencing instance method 'total()' on 'Array' requires that 'String' conform to 'Numeric'". One member can carry the requirement itself: `func median() -> Element? where Element: Comparable` inside a plain `extension Array` is a contextual `where` clause. A generic caller has to restate the requirement. Inside `func sumAll<T>(_ xs: [T])`, `xs.total()` fails until `T: Numeric` is declared. Making `Array` conform to a protocol under a condition is conditional conformance, which is a separate mechanism.
code
swift · 22 linesextension Array where Element: Numeric {
func total() -> Element {
reduce(.zero, +)
}
}
extension Array {
// Contextual where clause: only this member carries the requirement.
func median() -> Element? where Element: Comparable {
guard !isEmpty else { return nil }
return sorted()[count / 2]
}
}
extension Array where Element == String {
func joinedAsList() -> String { joined(separator: ", ") }
}
print([4, 8, 15].total()) // 27
print([2.5, 0.5].total()) // 3.0
print(["b", "c", "a"].median() ?? "-") // b
print(["tea", "cake"].joinedAsList()) // tea, cakego deeper
Recall the shape extension Array where Element: Numeric and that its members show up only on arrays that meet the requirement.
Explain that the body may use what the requirement promises, that a single member can carry a contextual where clause, and that the wrong element type fails at compile time.
Show how requirements propagate through generic callers, how overlapping extensions rank by specificity, and how this differs from conditional conformance.
Coach teams to put helpers on the narrowest requirement that works, so shared extensions do not clutter autocomplete on unrelated element types.
## What a constrained extension is An **extension** adds members to an existing type. A **constrained extension** adds a generic `where` clause, so its members exist only for the specializations that satisfy it: ```swift extension Array where Element: Numeric { func total() -> Element { reduce(.zero, +) } } ``` `[4, 8, 15].total()` returns `27`, and `[2.5, 0.5].total()` returns `3.0`. For `["tea", "cake"]` the method is not available at all. The type checker reports **"referencing instance method 'total()' on 'Array' requires that 'String' conform to 'Numeric'"** at the call. Nothing about `Array` itself changes. The extension does not make arrays numeric or alter their storage. It only adds API that some arrays can reach. ## What the body may assume Inside the extension, the `where` clause is a fact the compiler uses. `Numeric` refines `AdditiveArithmetic` (which supplies `.zero` and `+`) and `ExpressibleByIntegerLiteral`, so `reduce(.zero, +)` type-checks. The same body in an unconstrained `extension Array` would fail, because a bare `Element` has no `+`. | Extension header | Members exist for | Body may use | |---|---|---| | `extension Array where Element: Numeric` | `[Int]`, `[Double]`, ... | `.zero`, `+`, `*`, integer literals | | `extension Array where Element: Comparable` | `[Int]`, `[String]`, ... | `<`, `sorted()`, `max()` | | `extension Array where Element == String` | `[String]` only | every `String` API on elements | | `extension [String]` | `[String]` only | same as the line above (shorthand) | ## Contextual `where` clauses on a single member You do not need one extension per requirement. A member declared inside a generic context can carry its own `where` clause even though it declares no placeholders. This is a **contextual `where` clause**: ```swift extension Array { func median() -> Element? where Element: Comparable { guard !isEmpty else { return nil } return sorted()[count / 2] } } ``` `median()` exists only on arrays of `Comparable` elements. Calling it on `[Item]`, where `Item` is not `Comparable`, fails with "instance method 'median()' requires that 'Item' conform to 'Comparable'". If the enclosing extension has a `where` clause too, the member's requirements are **added** to it, and both must hold. ## Generic callers must restate the requirement The availability check happens wherever the call is written, and that includes inside other generic code: 1. `func sumAll<T>(_ xs: [T]) -> T { xs.total() }` fails with "referencing instance method 'total()' on 'Array' requires that 'T' conform to 'Numeric'". 2. The compiler does not look at who calls `sumAll`. Inside its body, `T` is unconstrained. 3. Declaring `func sumAll<T: Numeric>(_ xs: [T]) -> T` fixes it, and now every caller of `sumAll` must pass numeric elements. Requirements therefore **propagate outward** through every layer of generic code that wants to use the constrained member. The same holds inside generic types. In `struct Report<Row>` with a stored `rows: [Row]`, the expression `rows.total()` compiles only when `Report` declares `Row: Numeric`, or when the member that calls it carries its own contextual `where Row: Numeric`. ## Not to be confused with conditional conformance - A constrained extension adds **members**: `total()` on numeric arrays. - **Conditional conformance** (`extension Array: Summable where Element: Summable`) makes the type **conform to a protocol** under a condition, so `[Int]` can be passed where a `Summable` is expected. That mechanism, and how its dispatch works, belongs to the material on protocol default implementations. - Both use the same `where` syntax, so a reviewer should check whether a header has a `: Protocol` before the `where`. ## Pitfalls seen in review - Expecting a run-time failure for the wrong element type. The rejection is always at compile time. - Writing two extensions with the same method under overlapping requirements, such as `Element: Equatable` and `Element: Hashable`. For `[Int]` the more specific `Hashable` version wins, which surprises readers who expect the first one declared. - Constraining with `Element == Int` when `Element: BinaryInteger` would serve every integer type. - Reaching for a constrained extension when a free generic function with the same constraint would be clearer at the call site. - Reading the diagnostic as "method not found". The member exists, and the message names the unmet requirement, which tells you which conformance to add or which constraint to restate.
- Two extensions declare `summary()`, one `where Element: Equatable` and one `where Element: Hashable`. Which does `[1, 2].summary()` call?The `Hashable` one. Both are viable for `[Int]`, and overload ranking prefers the candidate with the more specific requirement. `Hashable` refines `Equatable`, so its version wins. An array of a type that is `Equatable` but not `Hashable` gets the other version. The choice is made at compile time from the static element type.
- How do you add API only to arrays of strings, and is there a shorter spelling?Use a same-type requirement on the element, `extension Array where Element == String`. The members then exist only on `[String]`, and inside them every element is a `String`. The bound-generic shorthand `extension [String]` means the same thing and has been accepted since Swift 5.7, which every current toolchain supports.
- A constrained extension makes Array itself conform to Numeric.
- Calling total() on [String] compiles and traps at run time.
- Inside a generic function, xs.total() works because every real caller passes numbers.
- Each requirement needs its own extension; a single method cannot carry a where clause.
- When two constrained extensions overlap, Swift calls the one declared first.