Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
subscript(parameter: ParameterType) -> ReturnType {
    get {
        // Return an appropriate value of ReturnType
    }
}
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.
subscript(parameter: ParameterType) -> ReturnType {
    // Return an appropriate value of ReturnType
}

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.
struct AbstractContainer {
    private var internalStorage: [Int]
    
    init(elements: [Int]) {
        self.internalStorage = elements
    }
    
    // Read-only subscript
    subscript(index: Int) -> Int {
        return internalStorage[index]
    }
}

let container = AbstractContainer(elements: [10, 20, 30])
let value = container[1] // Valid: Retrieves 20
// container[1] = 50     // Invalid: Compile-time error
Master Swift with Deep Grasping Methodology!Learn More