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.

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"

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