0Pricing
Swift Academy · Lesson

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 — 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.

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)  // -1

Multi-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.

Frequently asked questions

Is the “Subscripts for custom indexing” lesson free?

Yes — the full text of “Subscripts for custom indexing” 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 “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; 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 “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

  1. Properties & Subscripts
  2. lazy & property observers
  3. Computed properties with get/set
  4. Subscripts for custom indexing
← Back to Swift Academy