Subscripts for custom indexing
Define custom subscripts to read/write elements using array-like syntax, add safe accessors, support multi-parameter indexing, and even type (static) subscripts.
Subscripts for custom indexing is a free Swift Academy lesson on CoddyKit. This is lesson 4 of 4. 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 4 lessons in total.
Overview
Use subscripts to access data with bracket syntax. You can make them read-only or read–write and even accept multiple indices.
Read–write subscript
Create a get/set subscript to expose internal storage with array-like syntax.
struct Box {
private var items: [String] = []
init(_ values: [String]) { self.items = values }
subscript(index: Int) -> String {
get { items[index] } // may trap if out of bounds (like Array)
set { items[index] = newValue }
}
}
var b = Box(["a","b","c"])
print(b[1]) // "b"
b[1] = "B"
print(b[1]) // "B"Safe subscript
Return an optional to avoid traps on invalid indices: a friendly safe subscript.
extension Array {
subscript(safe i: Int) -> Element? {
return indices.contains(i) ? self[i] : nil
}
}
let arr = [10,20]
print(arr[safe: 1] ?? -1) // 20
print(arr[safe: 5] ?? -1) // -1Multi-parameter
Subscripts can take multiple parameters—great for matrices or coordinate access.
struct Matrix {
let rows: Int, cols: Int
private var grid: [Int]
init(rows: Int, cols: Int, fill: Int = 0) {
self.rows = rows; self.cols = cols
self.grid = Array(repeating: fill, count: rows*cols)
}
private func index(_ r: Int, _ c: Int) -> Int { r*cols + c }
subscript(r: Int, c: Int) -> Int {
get { grid[index(r,c)] }
set { grid[index(r,c)] = newValue }
}
}
var m = Matrix(rows: 2, cols: 3)
m[0, 2] = 7
print(m[0, 2])Type subscript
Add a type subscript (with static) to index on the type itself, not an instance.
struct Roman {
static let map: [Int:String] = [1:"I", 5:"V", 10:"X"]
static subscript(_ n: Int) -> String? {
return map[n]
}
}
print(Roman[5] ?? "?") // "V"Tips
Tips:
- Prefer returning optionals for safe access.
- Keep subscripts simple; heavy logic belongs in methods.
- Name parameters for clarity (e.g.,
[row:col:]).
Subscript meaning
Quick check: What do subscripts enable?
Recap
Recap: Build read–write subscripts, add safe optional accessors, support multi-parameter indexing, and even define type subscripts.
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 for custom indexing” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Subscripts for custom indexing”, 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 4 lessons in total.
What will I learn in “Subscripts for custom indexing”?
Define custom subscripts to read/write elements using array-like syntax, add safe accessors, support multi-parameter indexing, and even type (static) subscripts. 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 4 of 4.
How long does the “Subscripts for custom indexing” 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
- Properties & Subscripts
- lazy & property observers
- Computed properties with get/set
- Subscripts for custom indexing