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
- Properties & Subscripts
- lazy & property observers
- Computed properties with get/set
- Subscripts for custom indexing