Swift Academy · Lesson

Subscripts & custom indices revisited

Define subscripts with get / set , accept multiple parameters (e.g., 2D matrix), and use custom index types (enums) for readable APIs.

Lesson 2 of 38 steps

Subscripts & custom indices revisited is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 3 lessons in total.

What are subscripts?

Subscripts let instances be indexed like arrays. You can:

  • Expose read-only or read–write access
  • Accept multiple parameters (e.g., row/col)
  • Use custom indices like enums for clarity

Read-only subscript

A subscript can be read-only by returning a value without set.

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int { multiplier * index } // read-only
}
let t = TimesTable(multiplier: 3)
print(t[4]) // 12

Read–write with get/set

Add get/set for read–write access. Guard indexes to avoid crashes.

struct SafeArray<T> {
    private var storage: [T]
    init(_ xs: [T]) { self.storage = xs }
    subscript(i: Int) -> T? {
        get { (0..<storage.count).contains(i) ? storage[i] : nil }
        set {
            guard let v = newValue, (0..<storage.count).contains(i) else { return }
            storage[i] = v
        }
    }
}
var s = SafeArray([10,20,30])
print(s[1] ?? -1) // 20
s[1] = 99
print(s[1] ?? -1) // 99
s[5] = 7          // ignored (out of range)

2D indexing

Subscripts can take multiple parameters and use labels for clarity (e.g., row/col).

struct Matrix {
    let rows: Int, cols: Int
    private var grid: [Int]
    init(_ r: Int, _ c: Int, fill: Int = 0) {
        rows = r; cols = c; grid = Array(repeating: fill, count: r * c)
    }
    private func valid(_ r: Int, _ c: Int) -> Bool { r >= 0 && r < rows && c >= 0 && c < cols }
    subscript(row r: Int, col c: Int) -> Int {
        get { precondition(valid(r,c), "Index out of range"); return grid[r*cols + c] }
        set { precondition(valid(r,c), "Index out of range"); grid[r*cols + c] = newValue }
    }
}
var m = Matrix(2, 3)
m[row: 0, col: 1] = 5
print(m[row: 0, col: 1]) // 5

Custom index (enum)

Use custom indices to make intent obvious: an enum can map to storage while keeping API expressive.

enum Day: Int, CaseIterable { case mon = 0, tue, wed, thu, fri, sat, sun }
struct Week {
    private var tasks = Array(repeating: "—", count: Day.allCases.count)
    subscript(day: Day) -> String {
        get { tasks[day.rawValue] }
        set { tasks[day.rawValue] = newValue }
    }
}
var w = Week()
w[.wed] = "Ship"
print(w[.wed])

Design tips

Tips:

  • Prefer subscripts for element access; use methods for actions.
  • Validate indices (assert/precondition or safe optionals).
  • Name parameters for multi-axis access.
  • Keep subscripts fast and predictable.

Read–write declaration

Quick check: Which declares a read–write subscript?

Recap

Recap: Build read-only and read–write subscripts, accept multiple parameters (like matrices), and prefer custom indices (enums) for readability and safety.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Subscripts & custom indices revisited” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Subscripts & custom indices revisited”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 3 lessons in total.

What will I learn in “Subscripts & custom indices revisited”?

Define subscripts with get / set , accept multiple parameters (e.g., 2D matrix), and use custom index types (enums) for readable APIs. 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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 3.

How long does the “Subscripts & custom indices revisited” 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. Operator overloading & precedence groups
  2. Subscripts & custom indices revisited
  3. Hashable/Equatable/Comparable derivations
← Back to Swift Academy