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.
Subscripts & custom indices revisited is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. 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 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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]) // 12Read–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]) // 5Custom 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.
Frequently asked questions
Is the “Subscripts & custom indices revisited” lesson free?
Yes — the full text of “Subscripts & custom indices revisited” is free to read here on the web, and the Swift Academy course includes 3 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 “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; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
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
- Operator overloading & precedence groups
- Subscripts & custom indices revisited
- Hashable/Equatable/Comparable derivations