skip to content

In Swift, how do static and class type properties differ, and when does a stored static property get its initial value?

level: middleimportance: should knowfreq 45%

answer

  1. one copy per type
  2. class means overridable
  3. computed only for class
  4. first access, exactly once
  5. Swift 6 mode and static var

basics

~20 s

Both belong to the type, not an instance. static works in structs, enums and classes and cannot be overridden; class is only for computed properties of classes and is overridable. A stored static property initializes on first access, exactly once.

solid answer

~50 s

A **type property** has one copy per type. `static` declares stored or computed type properties in structs, enums and classes; in a class a `static` member is implicitly final, so overriding it fails with "cannot override static property". `class` declares an **overridable computed** type property in a class; `class var count = 0` is rejected with "class stored properties not supported in classes; did you mean 'static'?". A stored type property must have a default value, because the type has no initializer to set it, and the language guide guarantees it is **initialized lazily on first access, only once, even under simultaneous access**, with no `lazy` keyword. In the **Swift 6 language mode**, a mutable `static var` that is not isolated is an error, "static property '…' is not concurrency-safe because it is nonisolated global shared mutable state"; make it a `let`, isolate it to `@MainActor`, or protect it yourself.

code

swift · 22 lines
swift
struct Temperature {
    static let absoluteZeroCelsius = -273.15          // stored: lazy, once, thread-safe
    static var freezingPoint: Temperature {           // computed type property
        Temperature(celsius: 0)
    }
    var celsius: Double
}

class Sensor {
    class var unitSymbol: String { "C" }              // computed: overridable
    static let maxSampleRate = 10                     // stored: always static
}

final class FahrenheitSensor: Sensor {
    override class var unitSymbol: String { "F" }
}

print(Temperature.absoluteZeroCelsius)                // -273.15
print(Temperature.freezingPoint.celsius)              // 0.0
let sensors: [Sensor.Type] = [Sensor.self, FahrenheitSensor.self]
print(sensors.map { $0.unitSymbol })                  // ["C", "F"]
print(FahrenheitSensor.maxSampleRate)                 // 10

go deeper

for a junior

Recall that static properties belong to the type, are read through the type name, and that every instance sees the same value.

for a middle

Explain static versus class (stored versus overridable computed), why stored type properties need a default value, and their lazy, once-only initialization.

for a senior

Handle Swift 6 mode's errors on mutable static state with the right fix, let, global-actor isolation or real synchronization, and know when nonisolated(unsafe) is honest.

for a principal

Treat static mutable state as a design smell to budget for during a Swift 6 migration, preferring injected dependencies over globals reached through type properties.

## Type properties An **instance property** has a separate value in every instance. A **type property** belongs to the type itself: there is one copy no matter how many instances exist, and you read it through the type name, `Temperature.absoluteZeroCelsius`. Type properties can be stored or computed, and they are the Swift home for what other languages call static constants and class-level variables. Two keywords declare them: - `static` works in structures, enumerations and classes, for stored and computed type properties alike. - `class` works only in classes, only for **computed** type properties, and marks the property as overridable by subclasses. ## static versus class | | `static` | `class` | |---|---|---| | Allowed in | structs, enums, classes, protocols | classes only | | Stored property | Yes (`static let`, `static var`) | No: "class stored properties not supported in classes; did you mean 'static'?" | | Computed property | Yes | Yes | | Overridable by a subclass | No: in a class it is implicitly final | Yes, with `override class var` | | Typical use | constants, shared configuration, counters | a per-subclass answer, such as a unit symbol | In a class, `static` behaves like `class final`: a subclass that writes `override static var` gets "cannot override static property", and `static final let` is redundant ("static declarations are already final"). A constant type property of a class is always final, so `class let` is never possible. When a subclass needs its own value, declare a computed `class var` in the base and `override class var` in the subclass; the right override is chosen through the metatype, `sensors.map { $0.unitSymbol }`. The same split for type methods, and the general rules for `override`, are covered with methods and with subclassing. ## When stored type properties are initialized A stored type property must be given a **default value** in its declaration, because no initializer runs for the type itself. That default value is not evaluated at launch. The language guide states: - stored type properties are **initialized lazily on their first access**; - they are **guaranteed to be initialized only once**, even when several threads access them simultaneously; - they do **not** need the `lazy` modifier, and adding it is an error ("'lazy' cannot be used on an already-lazy global"). This makes `static let shared = Expensive()` the standard, thread-safe way to create a lazily built shared value, and the reason it is preferred over an instance `lazy var` for shared state. Only the initialization is protected; later reads and writes of a mutable `static var` are not synchronized by the language. ## Swift 6 language mode and mutable statics A mutable `static var` is global shared mutable state: any thread can read or write it. Since Swift 5.10 (SE-0412) the compiler checks this, and the check is part of the Swift 6 language mode: 1. **Swift 6 mode:** an unisolated `static var` is an error: "static property 'conversionsPerformed' is not concurrency-safe because it is nonisolated global shared mutable state". 2. **Swift 5 mode:** nothing by default; with complete concurrency checking (`-strict-concurrency=complete`) the same text appears as a warning, ending "this is an error in the Swift 6 language mode". The compiler's notes list the fixes, and each compiles in Swift 6 mode: - make it a `let` of a `Sendable` type, which is the usual answer for configuration; - isolate it to a global actor, `@MainActor static var`, when only main-actor code touches it; - mark it `nonisolated(unsafe)` only when an external lock really protects every access, because the compiler then stops checking. Access control does not help: a `private static var` gets the same error, because private code can still run on several threads. Isolation and `Sendable` belong to the material on concurrency; the point here is that type properties are where Swift 6 mode first complains in many codebases. ## Computed type properties A computed type property is written like a computed instance property with `static` or `class` in front, `static var freezingPoint: Temperature { Temperature(celsius: 0) }`. It runs on every access and stores nothing, so it raises no concurrency diagnostic of its own. A common shape is a computed `class var` that subclasses override, backed by `static let` constants they choose between.

  • Why can a class not declare a stored class var?
    class marks a type member as overridable through the class hierarchy, and Swift supports that only for computed type properties; a stored one is rejected with "class stored properties not supported in classes; did you mean 'static'?". Use static var for shared storage, or a computed class var that subclasses override.
  • How do you keep a mutable static counter in the Swift 6 language mode?
    Give it isolation or protection. If only main-actor code uses it, mark it @MainActor. Otherwise keep it in a Sendable, lock-protected value such as Mutex from the Synchronization module (Swift 6.0), or move it into an actor. nonisolated(unsafe) silences the check and is honest only when an external lock already guards every access.

  • class can declare stored type properties in a class.
  • Stored static properties are initialized when the app launches.
  • A static let needs the lazy keyword to be created on first access.
  • Subclasses can override static type properties of a class.
  • Making a mutable static var private satisfies Swift 6 mode's checks.

Assumes Swift 6.4: in the Swift 6 language mode an unisolated mutable static var is a compile error (SE-0412, since Swift 5.10), while Swift 5 mode reports it only as a warning under complete concurrency checking.