Skip to main content
A read-only subscript in Swift is a custom indexing interface that allows retrieval of values from an instance of a class, structure, or enumeration, but explicitly prohibits modification. It is defined by implementing only a getter within the subscript declaration and omitting the setter.

Syntax

Swift provides two ways to declare a read-only subscript: using an explicit get block, or using a shorthand syntax that omits the get keyword entirely. Explicit Getter Syntax:
Implicit Getter (Shorthand) Syntax: Because read-only subscripts are common, Swift allows the omission of the get block. The body of the subscript acts directly as the getter.

Technical Characteristics

  • Immutability Enforcement: Attempting to assign a value to a read-only subscript results in a compile-time error (Cannot assign through subscript: subscript is get-only).
  • Parameter Constraints: Subscripts can accept any number of input parameters of any type, including variadic parameters. However, they cannot use inout parameters or provide default parameter values.
  • Return Type: Unlike functions, subscripts must explicitly declare a return type. The getter must return an instance matching this declared type.
  • Overloading: You can define multiple read-only subscripts on the same type. The Swift compiler resolves which subscript to invoke based on the parameter signature passed at the call site.
  • Type Subscripts: By prefixing the subscript keyword with static (or class for class types), a read-only subscript can be applied to the type itself rather than an instance of the type.

Implementation Example

The following demonstrates a structure utilizing the shorthand read-only subscript syntax to expose internal storage without allowing external mutation.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More