0Pricing
Swift Academy · Lesson

Generic Subscripts and Extensions

Apply constraints to subscripts and extensions.

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]])

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