0Pricing
Swift Academy · Lesson

Generic Subscripts and Extensions

Apply constraints to subscripts and extensions.

Generic Subscripts and Extensions is a free Swift Academy lesson on CoddyKit — lesson 4 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.

Generic Subscripts

Subscripts can be generic, taking their own type parameters independent of the enclosing type. This lets one subscript serve many input types.

struct Lookup {
    let data = [1, 2, 3, 4, 5]
    subscript<S: Sequence>(indices idx: S) -> [Int] where S.Element == Int {
        idx.map { data[$0] }
    }
}
print(Lookup()[indices: [0, 2, 4]])

Why Generic Subscripts?

You can pass an Array, a Set, or a Range of indices to the same subscript because it accepts any Sequence of Int.

struct Lookup {
    let data = [10, 20, 30, 40]
    subscript<S: Sequence>(_ idx: S) -> [Int] where S.Element == Int {
        idx.map { data[$0] }
    }
}
let l = Lookup()
print(l[0...1])
print(l[[3, 0]])

Constrained Extensions

An extension ... where adds members that exist only when the constraint holds. They appear on the type only for matching generic arguments.

extension Array where Element: Numeric {
    func sumAll() -> Element { reduce(0, +) }
}
print([1, 2, 3].sumAll())
print([1.5, 2.5].sumAll())

Extension on a Specific Element Type

Use where Element == String to add String-specific helpers to arrays of strings only.

extension Array where Element == String {
    func shout() -> [String] { map { $0.uppercased() + "!" } }
}
print(["hi", "bye"].shout())

Constrained Extension with Protocol

Add behavior when elements conform to a custom protocol.

protocol Priced { var price: Double { get } }
struct Item: Priced { let price: Double }
extension Collection where Element: Priced {
    var total: Double { reduce(0) { $0 + $1.price } }
}
print([Item(price: 2), Item(price: 3)].total)

Generic Subscript Returning Optional

A subscript can be generic and return an optional, for example safe indexing into a collection.

extension Array {
    subscript(safe i: Int) -> Element? {
        indices.contains(i) ? self[i] : nil
    }
}
print([1, 2, 3][safe: 1] ?? -1)
print([1, 2, 3][safe: 9] ?? -1)

Generic Subscript on Dictionary

Generic subscripts can accept a sequence of keys and return the matching values.

extension Dictionary {
    subscript<S: Sequence>(keys ks: S) -> [Value] where S.Element == Key {
        ks.compactMap { self[$0] }
    }
}
let d = ["a": 1, "b": 2, "c": 3]
print(d[keys: ["a", "c"]].sorted())

Combining with where on Self

Extensions on generic types can constrain the wrapped type, exposing tailored APIs.

struct Stack<T> { var items: [T] = [] }
extension Stack where T: Comparable {
    var peakMax: T? { items.max() }
}
var s = Stack<Int>(); s.items = [3, 9, 1]
print(s.peakMax!)

Generic Subscript with Multiple Params

A subscript may take several arguments and its own type parameters together.

struct Grid {
    let rows = [[1, 2], [3, 4]]
    subscript(_ r: Int, _ c: Int) -> Int { rows[r][c] }
}
print(Grid()[1, 0])

Read-Only vs Read-Write

Like properties, subscripts can have a get only, or both get and set for mutation.

struct Pad {
    var values = [0, 0, 0]
    subscript(i: Int) -> Int {
        get { values[i] }
        set { values[i] = newValue }
    }
}
var p = Pad(); p[1] = 7
print(p.values)

Putting It Together

Generic subscripts plus constrained extensions let you build expressive, type-safe APIs that adapt to whatever element or argument types are used.

extension Array where Element: Comparable {
    subscript(topAfterSort i: Int) -> Element { sorted()[i] }
}
print([5, 1, 9, 3][topAfterSort: 0])

Quick Check

Test your understanding of generic subscripts and constrained extensions.

Recap

Generic subscripts declare their own type parameters and where clauses, letting one subscript accept many input types. Constrained extensions (where Element: ... or == ...) add members only when conditions hold. Together they build type-safe, adaptable APIs.

Frequently asked questions

Is the “Generic Subscripts and Extensions” lesson free?

Yes — the full text of “Generic Subscripts and Extensions” 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 “Generic Subscripts and Extensions”?

Apply constraints to subscripts and extensions. 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 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Generic Subscripts and Extensions” 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