How do you declare a Swift subscript that reads and writes `grid[row, column]`, and how do subscript argument labels differ from a method's?
answer
- subscript keyword, get and set
- newValue in the setter
- labels are off by default
- overloads, no inout
- static subscripts on the type
basics
~20 sDeclare subscript(row: Int, column: Int) -> Double with a get and a set block; the setter receives newValue. Unlike a method's parameters, a subscript's parameters have no argument labels unless you write one explicitly, so callers write grid[1, 2].
solid answer
~50 sA subscript is declared with the `subscript` keyword, a parameter list and a return type, like a method, and with `get` and `set` blocks like a computed property: `subscript(row: Int, column: Int) -> Double { get { … } set { cells[row * columns + column] = newValue } }`. Leave out `set` and you can drop the `get` braces for a read-only subscript. The key difference from a method is labels: subscript parameters have no argument labels by default, so callers write `grid[1, 2]`, and `grid[row: 1, column: 2]` fails with "extraneous argument labels 'row:column:' in subscript". Write an explicit label to require one: `subscript(row row: Int)` is called as `grid[row: 1]`. A type may overload subscripts by parameter or return type, parameters can be variadic or have defaults but not `inout`, and since Swift 5.1 a `static subscript` lets you write `Theme["accent"]` on the type itself.
code
swift · 35 linesstruct Matrix {
let rows: Int, columns: Int
private var cells: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
cells = Array(repeating: 0, count: rows * columns)
}
// Two parameters, no argument labels at the call site: m[1, 2]
subscript(row: Int, column: Int) -> Double {
get { cells[row * columns + column] }
set { cells[row * columns + column] = newValue }
}
// Explicit label, read-only: m[row: 1]
subscript(row row: Int) -> [Double] {
Array(cells[row * columns ..< (row + 1) * columns])
}
}
enum Theme {
private static let colors = ["accent": "teal", "background": "white"]
// Type subscript: Theme["accent"]
static subscript(name: String) -> String {
colors[name, default: "black"]
}
}
var grid = Matrix(rows: 2, columns: 3)
grid[0, 1] = 1.5
grid[1, 2] += 2
print(grid[0, 1], grid[row: 1], Theme["accent"]) // 1.5 [0.0, 0.0, 2.0] tealgo deeper
Recall the subscript keyword, the get and set blocks with newValue, and that grid[1, 2] needs no labels.
Explain the label rule and how to add an explicit label, overloading by type, the no-inout restriction, and that a struct's subscript setter is mutating.
Design subscripts that read like the domain: labelled overloads such as safe:, clear bounds failures, and a static subscript only where shared lookup state is genuinely global.
Judge whether bracket syntax helps a type's API or hides cost; a subscript reads as cheap access, so expensive work behind one misleads callers.
## What a subscript is A **subscript** gives a type the bracket syntax that `Array` and `Dictionary` use: `values[2]`, `scores["ana"]`. Classes, structures and enumerations can all declare one. A subscript sits between a method and a computed property: - like a **method**, it takes parameters and declares a return type; - like a **computed property**, it has a `get` block for reading and an optional `set` block for writing. The setter receives the assigned value as `newValue` unless you name the parameter yourself, and its type is the subscript's return type. If you only need reading, you can omit the `get` keyword and its braces and return the value directly. A setter without a getter is not allowed. ## A two-dimensional subscript A `Matrix` that stores its cells in a flat array can expose `grid[row, column]` with one subscript taking two parameters: ```swift subscript(row: Int, column: Int) -> Double { get { cells[row * columns + column] } set { cells[row * columns + column] = newValue } } ``` Assignments such as `grid[0, 1] = 1.5` call the setter, and compound assignments such as `grid[1, 2] += 2` read through the getter and write the result back through the setter. Bounds are your responsibility: the backing `Array` traps on an out-of-range index, but a flat array only catches indexes past its end — `grid[0, 5]` on a 2×3 matrix lands inside it. The Swift book's own `Matrix` example therefore asserts that the row and column are valid, a check that runs in debug builds. On a structure, a subscript setter is **implicitly mutating**, so assigning through it needs a `var`; on a `let` matrix the compiler reports `cannot assign through subscript: 'grid' is a 'let' constant`. If the subscript has no setter, assignment fails with `cannot assign through subscript: subscript is get-only`. ## Argument labels: the rule that differs from methods Subscript parameters follow the rules of function parameters, with **two exceptions** spelled out in the Swift reference: 1. **No argument labels by default.** A method `func cell(row: Int, column: Int)` is called `cell(row: 1, column: 2)`, but `subscript(row: Int, column: Int)` is called `grid[1, 2]`. The names are parameter names only. Writing the labels anyway reports `extraneous argument labels 'row:column:' in subscript`. 2. **No `inout` parameters.** `subscript(x: inout Int)` is rejected with `'inout' may only be used on function or initializer parameters`. To require a label, write it explicitly, exactly as for a function: `subscript(row row: Int) -> [Double]` is called `grid[row: 1]`, and `subscript(safe row: Int, _ column: Int)` is called `grid[safe: 4, 0]`. Explicit labels are how a type offers several readable subscripts side by side. Variadic parameters and default parameter values work as they do for functions. ## Overloading A type can declare as many subscripts as it needs; Swift picks one from the argument types and labels at the call site. Two subscripts may also differ only in **return type**, as the reference allows, but then the call needs a type context: `let s: String = lookup[1]` works, while `let x = lookup[1]` fails with `ambiguous use of 'subscript(_:)'` — a diagnostic that also shows the default label is `_`. | Feature | Methods | Subscripts | |---|---|---| | Argument labels by default | the parameter name is the label | none; add one explicitly | | `inout` parameters | allowed | not allowed | | Read-write access | two separate methods | one declaration with `get` and `set` | | Overloading | by labels, types or return type | by labels, types or return type | | Type-level form | `static func` / `class func` | `static subscript` / `class subscript` | ## Type subscripts Since Swift 5.1 (SE-0254) a subscript can be declared `static`, or `class` inside a class, and is then called on the type: `Theme["accent"]`, or equivalently `Theme.self["accent"]`, since static members are members of the metatype. A type subscript can be read-only or read-write; a read-write one needs mutable type-level storage behind it, which Swift 6 language mode checks for data races like any other mutable static state. The motivating case in the proposal is global key-value state such as process environment variables. A type subscript is useful for a small shared lookup — a theme palette, a registry keyed by name — without creating a singleton instance just to get bracket syntax. As with type methods, `class subscript` may be overridden by a subclass and `static subscript` in a class cannot. Generic subscripts, key-path subscripts and dynamic member lookup build on the same declaration, and are covered with generics and with key paths respectively.
- Why does `let grid = Matrix(rows: 2, columns: 2); grid[0, 1] = 1.5` fail when `Matrix` is a struct?A subscript setter on a value type is implicitly mutating, like a mutating method, so it needs write access to the value. A `let` constant grants none, and the compiler rejects the assignment. Declare `var grid`, or make `Matrix` a class if instances should be shared.
- When is a `static subscript` a better choice than a static method such as `Theme.color(named:)`?When the type exposes a lookup that reads like a collection: `Theme["accent"]` mirrors dictionary access, and it can have a setter so `Theme["accent"] = …` reads naturally. A static method is clearer when the operation takes several differently-labelled arguments or performs work beyond a lookup. Static subscripts need Swift 5.1 or later.
- Says subscript parameters use their names as argument labels like methods
- Believes a subscript can only take a single Int index
- Claims subscripts can declare inout parameters
- Thinks a subscript can have a setter without a getter
- Says subscripts cannot be declared on the type itself