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 theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
subscript declaration and omitting the setter.
Syntax
Swift provides two ways to declare a read-only subscript: using an explicitget block, or using a shorthand syntax that omits the get keyword entirely.
Explicit Getter Syntax:
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
inoutparameters 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
subscriptkeyword withstatic(orclassfor 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.Master Swift with Deep Grasping Methodology!Learn More





