Skip to main content
A static subscript is a subscript defined on a type itself rather than on an instance of that type. It allows indexing directly into a class, structure, or enumeration using the type name, providing a mechanism to query or mutate type-level data.

Syntax

A static subscript is declared using the static keyword preceding the subscript keyword.
For classes, you can use the class keyword instead of static if you need to allow subclasses to override the subscript implementation.

Technical Characteristics

  • Execution Context: Static subscripts execute in a type context. Within the subscript’s get or set blocks, the implicit self property refers to the type itself, not an instance.
  • Scope Restrictions: Because they operate at the type level, static subscripts can only directly access other static or class properties and methods. They cannot access instance properties or instance methods.
  • Mutability: Like instance subscripts, static subscripts can be read-only (by providing only a get block or omitting the get keyword entirely for a shorthand read-only declaration) or read-write (by providing both get and set blocks).
  • Overloading: A type can define multiple static subscripts provided their parameter signatures (the number, order, or types of parameters) are distinct.
  • Access Control: Standard Swift access control modifiers (open, public, internal, fileprivate, private) apply to static subscripts and can be applied to the set block independently to restrict mutation visibility (e.g., private(set)).

Implementation Mechanics

The following demonstrates the mechanics of declaring and invoking a static subscript to manage underlying static state.

Polymorphic Behavior in Classes

When applied to classes using the class modifier, static subscripts participate in dynamic dispatch, allowing subclasses to provide specialized implementations.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More