Fix: Cannot Extend Typed Array in Swift — Use Generic Where Clauses

Fix: Cannot Extend Typed Array in Swift — Use Generic Where Clauses

Written by

in

Quick answer: Swift does not allow extension Array<T> because T is unresolved at the extension site. Instead, constrain the extension with where Element == YourType for concrete types or where Element: YourProtocol for protocol conformance. This preserves type safety and works with structs, classes, and enums.

Why this happens

Swift arrays are generic structs: struct Array<Element>. When you write extension Array<T>, the compiler treats T as a new, unbound type parameter — not the array’s existing Element. That is why you see “Use of undefined type ‘T’”.

The older T[] syntax (pre-Swift 3) was a shorthand for Array<T> and could not be extended directly either; the compiler emits “Nominal type T[] can’t be extended”.

An unconstrained extension Array { … } compiles, but every method inside sees Element as Any (or an opaque placeholder), so you lose static type information and must cast at call sites.

How to fix it

1. Extend arrays of a concrete type with where Element == Type

Use a same-type constraint on Element. This works for classes, structs, enums, and type aliases.

struct HighScoreEntry: Equatable {
    let score: Int
    let player: String
}

extension Array where Element == HighScoreEntry {
    func sortedByScore() -> [HighScoreEntry] {
        sorted { $0.score < $1.score }
    }

    func top(_ k: Int) -> [HighScoreEntry] {
        Array(sortedByScore().prefix(k))
    }
}

// Usage
let scores = [
    HighScoreEntry(score: 100, player: "Ada"),
    HighScoreEntry(score: 250, player: "Grace"),
    HighScoreEntry(score: 180, player: "Alan")
]
let topThree = scores.top(3)   // [HighScoreEntry] — fully typed

Key points
– The constraint where Element == HighScoreEntry tells the compiler: “this extension only applies when the array holds exactly this type.”
– Inside the extension, Element is known to be HighScoreEntry, so you can access its properties without casting.
– The return type [HighScoreEntry] is inferred; you can also write [Element] for brevity.

2. Extend arrays whose elements conform to a protocol

When you need the same logic for any type that satisfies a protocol, constrain Element to that protocol.

protocol Scorable {
    var score: Int { get }
}

extension Array where Element: Scorable {
    func sortedByScore() -> [Element] {
        sorted { $0.score < $1.score }
    }
}

struct GameResult: Scorable { let score: Int; let level: Int }
struct QuizResult: Scorable { let score: Int; let topic: String }

let mixed: [any Scorable] = [GameResult(score: 10, level: 1), QuizResult(score: 5, topic: "Swift")]
// mixed.sortedByScore()  // ❌ heterogeneous array — Element is `any Scorable`, not a concrete Scorable

let games = [GameResult(score: 10, level: 1), GameResult(score: 5, level: 2)]
games.sortedByScore()   // ✅ [GameResult] — homogeneous array of a concrete Scorable type

Note: The protocol constraint only matches homogeneous arrays where Element is a single concrete type conforming to the protocol. An array of any Scorable (existential) does not satisfy Element: Scorable.

3. Add reusable algorithms on Sequence / Collection instead of Array

If the operation only needs iteration, extend Sequence or Collection so it works on arrays, sets, slices, and lazy views.

extension Sequence where Element: Scorable {
    func maxScore() -> Element? {
        self.max { $0.score < $1.score }
    }
}

let best = games.maxScore()   // Optional<GameResult>

This is how the standard library implements filter, map, sorted, etc. — on Sequence/Collection with where constraints.

4. Avoid the pre-Swift 3 SequenceType / Generator.Element spelling

The accepted answer shows SequenceType where Generator.Element == …. That was Swift 2.x. Since Swift 3 the protocols are Sequence / IteratorProtocol and the associated type is Iterator.Element (or simply Element on Sequence). Use the modern spelling:

extension Sequence where Element == HighScoreEntry { … }
// or
extension Sequence where Element: Scorable { … }

How to prevent it

  • Default to where Element == ConcreteType for type-specific helpers.
  • Prefer where Element: Protocol when the logic only uses protocol requirements.
  • Extend Sequence/Collection instead of Array unless you need array-specific APIs (append, remove(at:), subscript assignment).
  • Never write extension Array<T> — the <T> introduces a new, unrelated generic parameter.
  • Test with a heterogeneous existential array ([any MyProtocol]) to confirm your constraint behaves as expected.

FAQ

Why does extension Array { func find<T>(…) } still compile but lose types?

The method introduces its own generic parameter T that is independent of the array’s Element. The compiler infers T from the closure you pass, but there is no link back to Element, so the return type [T] is unrelated to the original array contents.

Can I extend Array for a type alias like typealias Point = (x: Int, y: Int)?

Yes. extension Array where Element == Point { … } works because a type alias is exactly the underlying type. The constraint matches the structural tuple type.

What if I need different behavior for class vs. struct elements?

Swift does not let you constrain Element to AnyObject and a concrete type simultaneously. Write two separate extensions:

extension Array where Element: AnyObject, Element == MyClass { … } // redundant
// Instead:
extension Array where Element == MyClass { … }           // class
extension Array where Element == MyStruct { … }          // struct

If the logic is identical, factor it into a protocol and constrain to that protocol.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.