Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 146 ยท Structures, Classes and Enums

Subscripts

Learn Swift subscripts - read-only and read-write access, multiple parameters, argument labels, static subscripts, generic subscripts, safe indexing and @dynamicMemberLookup.

You already use subscripts every day. scores[0] reads the first element of an array, ages["Ada"] looks up a dictionary key, and text[text.startIndex] fetches a character. The square brackets are not special syntax built into arrays; they call a function that the type defines. In Swift you can define such a function for your own types with the subscript keyword, so that a matrix, a spreadsheet, a game board or a configuration object can be read with the same short, familiar notation.

A subscript is a bit like a method and a bit like a computed property. It takes parameters in square brackets, it returns a value, and it can optionally accept an assignment. This lesson covers read-only and read-write subscripts, subscripts with several parameters, labels, defaults, static subscripts, generic subscripts, the common "safe index" extension, and @dynamicMemberLookup. It builds on structs, properties and methods.

A first subscript

A subscript is declared inside a struct, class or enum. The parameter list looks like a function's, then comes an arrow and the result type, then a body in braces. If the body is a single expression, it is returned just as in a function:

Swift A read-only subscript

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

threeTimes[6] calls the subscript with index set to 6. There is no stored table; the answer is computed on demand, exactly like a computed property. Notice that the parameter is written index: Int, but the call is threeTimes[6] with no label. That is the first difference from a method, and it is covered below.

Read-write subscripts

To allow thing[i] = value, give the subscript a get and a set. Inside set, the new value is available under the name newValue, unless you name it yourself with set(name):

Swift get and set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The songs array is private, so the outside world reaches the data only through the subscript. That gives the type a place to enforce rules, as the next example does. list is a var because Playlist is a struct, and assigning through a subscript counts as mutating it. If you wrote let list, the line list[1] = "Chorus" would not compile.

A subscript with only a getter is read-only, and you can drop the word get as above. A subscript can also have a private(set) setter if the type itself must be the only writer.

Out of range: a trap, not an exception

The built-in array subscript stops the program if you ask for an index that does not exist. Swift treats that as a programmer error, not as something to recover from:

Swift An index out of range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints and the second crashes. Because the runner uses an optimized build, you get no "Index out of range" text; the process ends with a trap signal (SIGILL) and a backtrace, and a note about the non-zero exit code. In a debug build you would see Fatal error: Index out of range. Either way, the lesson is the same: when you write your own subscript, decide whether a bad index is a bug (trap, like the array) or an expected situation (return an optional).

Multiple parameters

A subscript may take several parameters of any type. This is ideal for grids, where you want grid[row, column]:

Swift A matrix with two indices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The values live in one flat array, and the subscript converts (row, column) into a single index with row * columns + column. Callers never see that detail. precondition guards the bounds with a message, and += works because Swift reads through the getter and writes through the setter. If you would rather handle bad indices gently, make the result an optional. We will do that in a moment.

Argument labels in subscripts

Unlike functions, subscript parameters have no argument label by default. If you want one, write it twice, an external name and an internal name, as with a function:

Swift Labels on subscript parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Labels also let one type have several subscripts with the same parameter types but different meanings. You can overload subscripts: Swift chooses by the number and types of arguments, and by labels. Use a label when the bare bracket would be ambiguous or confusing, for instance calendar[day: 3] is clearer than calendar[3].

Default values and returning optionals

Dictionary has two subscripts that show a useful pair of designs. dict[key] returns an optional, because the key might be missing. dict[key, default: value] returns a non-optional, because the default fills the gap. You can give subscript parameters default values too, and you can model the same pair yourself.

Here is the "safe index" extension that many Swift programmers add to collections. It adds a subscript with a label so that it never crashes:

Swift A safe subscript extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The extension works on every collection (arrays, strings, sets, dictionaries' keys...). It uses the indices property to check validity first. The call site colors[safe: 5] ?? "none" reads nicely with the nil-coalescing operator. Do keep in mind that indices.contains can be slow on collections where it is not constant time, and that hiding an out-of-range error means you can also hide a real bug. Use it for input that really can be out of range, not to silence crashes.

Extensions are a good way to add subscripts to types you do not own, as long as the label makes the intent obvious. See Nested Types and Extensions for more on extending types.

Static (type) subscripts

A subscript can belong to the type rather than to an instance. Use the static keyword, and call it on the type name. A typical use is a lookup table or a registry:

Swift A static subscript

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Static subscripts are less common than instance subscripts, but they give a pleasant syntax for type-level lookups. Note the private static let. A mutable static var is global state, and in Swift 6 language mode the compiler rejects it with error: static property 'store' is not concurrency-safe because it is nonisolated global shared mutable state. A constant dictionary is safe to share; for a settings store that can change, use an actor or a lock, as explained in Sendable and Data Races.

Generic subscripts

Like functions, subscripts can have their own generic parameters and where clauses. A classic use is a heterogeneous store where the caller says which type they expect:

Swift A generic subscript

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first subscript is generic over T; the argument Int.self tells the compiler which type to look for, and as? T returns nil when the stored value has a different type. The second subscript accepts any sequence of strings. Generic subscripts are an advanced tool. Reach for them when a plain subscript cannot express the relationship between input and output types.

Subscripts and key paths

Every subscript that takes a Hashable parameter can also be used inside key paths, for example \.[0] for "the first element". The standard library relies on this in places, and Key Paths shows more. For now it is enough to know that subscripts are first-class members of a type.

@dynamicMemberLookup

Sometimes you want property-style access (config.timeout) for names that are only known at run time. The attribute @dynamicMemberLookup lets a type handle any unknown .name with a special subscript, subscript(dynamicMember:):

Swift Dynamic member lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler turns config.host into config[dynamicMember: "host"]. The price is that typos are no longer compile errors: config.hots compiles and returns (not set). Dynamic member lookup is useful for wrappers around dynamic data (JSON, scripting bridges) and for forwarding to a wrapped value through key paths, but it removes a layer of safety, so use it sparingly. Dynamic Features covers it in more depth.

When to write a subscript

Write a subscript when your type is a container or a lookup and the natural question is "what is at this position/key?". Matrices, boards, buffers, caches and sparse tables are good examples. Prefer a named method when the operation does real work or has side effects, and prefer a property when there is no parameter. Keep subscripts cheap and predictable: callers expect x[i] to be fast and free of surprises, ideally constant time. And decide the failure mode deliberately: trap for programmer error, nil for an expected miss.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call correctly uses subscript(row: Int, column: Int) -> Double with no custom labels?

    Subscript parameters have no argument labels by default, so you pass the values separated by commas inside the brackets.
  2. 2. How do you add an argument label to a subscript parameter?

    As with function parameters, writing two names gives the first as the external label. The call becomes week[day: 3].
  3. 3. What is the name of the incoming value inside a subscript set block when you do not name it?

    The setter receives the assigned value as newValue, just like a computed property setter. You may rename it with set(name).
  4. 4. What does the built-in Array subscript do for an index that is out of range?

    An invalid array index is treated as a programmer error and traps. Design your own subscripts to trap or return an optional on purpose.
  5. 5. What is the main risk of @dynamicMemberLookup?

    The compiler cannot check names that are resolved through subscript(dynamicMember:), so a typo is not caught until the program runs.

Summary

  • A subscript lets a type use value[index] notation; it is declared like a function with an arrow and a result type, and acts like a computed property.
  • Read-only subscripts only need a body; read-write subscripts have get and set, with the assigned value named newValue.
  • Subscripts can take several parameters (grid[row, column]) and can be overloaded.
  • Subscript parameters have no argument labels unless you write an external name.
  • Out-of-range access either traps (like Array) or returns an optional; choose deliberately, or add a safe subscript through an extension.
  • static subscript belongs to the type; generic subscripts have their own type parameters.
  • @dynamicMemberLookup routes value.name to subscript(dynamicMember:) at the cost of compile-time name checks.

Next: Optional Chaining in Depth