Skip to main content
A static property in Swift is a type-level property associated with the defining type itself, rather than with any individual instance of that type. Memory for a stored static property is allocated only once, meaning all instances of the type share the exact same underlying state and memory address.

Declaration and Syntax

Static properties are declared using the static keyword. They can be implemented as either stored properties or computed properties within structures, classes, enumerations, and protocols.

Initialization and Memory Semantics

  • Lazy Initialization: Stored static properties are inherently lazily initialized. Memory allocation and assignment do not occur until the exact moment the property is first accessed in the execution flow. The lazy modifier is neither required nor permitted.
  • Thread Safety: The Swift runtime guarantees that the initialization of a stored static property is thread-safe. If multiple threads attempt to access an uninitialized static property simultaneously, the runtime ensures the initialization closure or assignment is executed exactly once.
  • Default Values: Because types themselves do not possess initializers in the way instances do, stored static properties must be assigned a default value at the point of declaration.

Accessing Static Properties

Static properties are accessed and mutated by querying the type directly using dot notation. They cannot be accessed through an instance of the type.

static vs. class Modifiers

In the context of class types, Swift provides two distinct modifiers for type properties: static and class.
  • static: Defines a type property that is statically dispatched. It cannot be overridden by subclasses. It is valid for both stored and computed properties.
  • class: Defines a type property that is dynamically dispatched, allowing subclasses to override the implementation. The class modifier can only be applied to computed properties; Swift does not support stored class properties.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More