skip to content

Stored and Computed Properties

Properties store values, compute them on access, react through willSet and didSet, or load lazily. Interviewers ask when observers fire, what lazy costs and static versus class.

on this pageshow

explore

questions

6

In Swift, what is the difference between a stored property and a computed property, and how is a read-only computed property declared?

level: juniorimportance: must knowfreq 70%

answer

  1. memory versus code
  2. get and set accessors
  3. the setter's implicit parameter name
  4. getter only, still var

basics

~20 s

A stored property holds a value in each instance's memory; a computed property stores nothing and runs its getter, and optional setter, on every access. A read-only computed property has only a getter and is still declared with var.

solid answer

~50 s

A **stored property** is a constant (`let`) or variable (`var`) whose value lives inside every instance. A **computed property** has no storage: it is a `get` accessor, and optionally a `set` accessor, that runs every time the property is read or written, usually deriving its value from stored properties. A setter receives the incoming value as `newValue` unless you name the parameter. A **read-only computed property** has a getter and no setter; you can drop the `get` keyword and, when the body is a single expression, the `return` too. It is still declared with `var`, because `let` means a value fixed at initialization: `let` on a computed property is the compile error "'let' declarations cannot be computed properties", and assigning to a read-only one fails with "is a get-only property". A `Temperature` that stores `celsius` and computes `fahrenheit` keeps one source of truth.

code

swift · 18 lines
swift
struct Temperature {
    var celsius: Double

    var fahrenheit: Double {
        get { celsius * 9 / 5 + 32 }
        set { celsius = (newValue - 32) * 5 / 9 }
    }

    var isFreezing: Bool { celsius <= 0 }
}

var today = Temperature(celsius: 20)
print(today.fahrenheit)     // 68.0
today.fahrenheit = 212
print(today.celsius)        // 100.0
print(today.isFreezing)     // false
let frozen = Temperature(celsius: -5)
print(frozen.isFreezing)    // true

go deeper

for a junior

Recall that stored properties hold memory and computed properties run a getter on every access. Know newValue, the shorthand getter, and that read-only computed properties still use var.

for a middle

Explain why let cannot declare a computed property, why extensions accept computed but not stored properties, and that a struct's computed setter mutates the instance.

for a senior

Show judgment about derived state: compute instead of storing two copies that drift, and notice when an expensive getter read in a loop should become stored state or a method.

for a principal

Frame properties as API surface: a computed property promises cheap, side-effect-free reads, so a team rule might push expensive or failing work into methods where its cost is visible.

## Two kinds of instance property Every Swift structure, class and enumeration can declare **properties**: named values that belong to an instance. Swift has two kinds, and the difference is whether the instance carries memory for the value. - A **stored property** is a `let` constant or a `var` variable that occupies space in every instance. Each instance has its own copy (for a structure) or its own field (for a class), and it must hold a value by the time initialization finishes, either from a default value in the declaration or from the initializer. - A **computed property** stores nothing. It is a pair of accessor functions that look like a property to the caller: a `get` accessor that returns a value and an optional `set` accessor that receives one. Enumerations are the exception worth remembering: they can declare computed properties but not stored instance properties. ## Writing a computed property A computed property always has an explicit type annotation and a body in braces: ```swift struct Temperature { var celsius: Double // stored var fahrenheit: Double { // computed, read-write get { celsius * 9 / 5 + 32 } set { celsius = (newValue - 32) * 5 / 9 } } } ``` Points that interviewers check: 1. The **getter** runs on every read. Nothing is cached; reading `fahrenheit` twice performs the arithmetic twice. 2. The **setter** receives the incoming value. If you write `set` without a parameter name, Swift supplies the name `newValue`; you may write `set(newFahrenheit)` to name it yourself. 3. If a getter's whole body is a **single expression**, it returns that expression implicitly (the shorthand getter, available since Swift 5.1), so `get { celsius * 9 / 5 + 32 }` needs no `return`. 4. Writing through the setter usually changes stored state. In the example, assigning `fahrenheit = 212` sets `celsius` to `100`; there is no `fahrenheit` field anywhere. In a structure, a computed setter is a mutating operation, so it cannot be used on an instance bound with `let`: the compiler reports "cannot assign to property: 't' is a 'let' constant", exactly as for a stored `var`. ## Read-only computed properties A computed property with a getter and no setter is a **read-only computed property**. The `get` keyword and its braces may be dropped: ```swift var isFreezing: Bool { celsius <= 0 } ``` It must still be declared with `var`. The keyword `let` promises a value fixed during initialization, which a computed property cannot promise, so `let isFreezing: Bool { celsius <= 0 }` fails with "'let' declarations cannot be computed properties". Assigning to a read-only property fails with "cannot assign to property: 'isFreezing' is a get-only property". The reverse shape, a setter with no getter, is also rejected: "variable with a setter must also have a getter". ## Stored versus computed at a glance | Question | Stored property | Computed property | |---|---|---| | Takes memory in each instance? | Yes | No | | Declared with | `let` or `var` | `var` only | | Runs code on access? | Only observers, on writes | Yes, every access | | Allowed in an extension? | No | Yes | | Allowed in an enumeration? | Only as a type property | Yes | | Can be read-only? | Use `let` | Omit the setter | The extension row is a frequent follow-up. An extension cannot change a type's memory layout, so a stored property there fails with "extensions must not contain stored properties", while a computed property is just a pair of functions and is allowed. ## Choosing one - **Derive instead of duplicating.** If a value can be computed cheaply from other properties, make it computed. Storing both `celsius` and `fahrenheit` invites the two to drift apart; computing one from the other keeps a single source of truth. - **Watch the cost.** Because the getter runs on every access, an expensive computation read in a loop is repeated each time. If the work is costly and its inputs rarely change, store the result explicitly and update it, or turn it into a method so the cost is visible at the call site. - **Prefer a property when it reads like a value.** A computed property should behave like data: no parameters, no observable side effects, and cheap enough that a caller would not think twice about reading it. If reading it can fail or must wait, the lesson on effectful getters covers `get throws` and `get async`. Computed properties also show up beside other property features. Observers (`willSet` and `didSet`) belong to stored properties; a computed property you declare does its reacting inside its own setter. Lazy stored properties are a third option, for a value stored but created on first use.

  • Why can an extension add a computed property to a Swift type but not a stored one?
    An extension cannot change the memory layout of the type it extends, and a stored property needs space in every instance, so the compiler rejects it with "extensions must not contain stored properties". A computed property is only a getter and an optional setter, which are functions, so extensions may add them freely.
  • When would you store a derived value instead of computing it on every access?
    When computing it is expensive and it is read far more often than its inputs change. A computed property reruns its getter on every read, so a costly getter in a loop repeats the work. Storing the result trades that cost for the duty to keep it in sync, usually by updating it whenever an input changes.
  • Can you assign to a read-write computed property of a struct held in a let constant?
    No. On a structure, a computed setter mutates the instance just as assigning a stored var does, so the compiler reports "cannot assign to property: 't' is a 'let' constant". Binding the instance with var, or making the type a class, allows the assignment.

  • A computed property caches its result after the first read.
  • A read-only computed property should be declared with let.
  • A computed property takes up storage in every instance.
  • An extension can add a stored property if you give it a default value.
  • A setter must declare its parameter name; there is no default name.
open as a page

In Swift, when are a property's willSet and didSet observers called, and when does Swift skip them?

level: middleimportance: must knowfreq 60%

basics

~20 s

willSet runs just before a new value is stored and didSet right after, on every assignment outside initialization, even when the value is unchanged. They are not called while a type's own initializer sets the property.

open as a page

In Swift, what does marking a stored property lazy do, and why must a lazy property be declared with var?

level: middleimportance: should knowfreq 55%

basics

~20 s

A lazy stored property runs its initial-value expression on first access instead of during initialization, then keeps the result. It must be var because it gets its value after initialization ends, which a let constant cannot do.

open as a page

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%

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.

open as a page

A Swift SettingsStore class saves to disk in didSet on its recentFiles array; why do three appends write three times while its initializer writes nothing?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Mutating part of a value-typed property, such as an append or a nested field write, writes the whole property, so didSet runs once per mutation. Assignments in the type's own initializer skip observers, so nothing saves there.

open as a page

In Swift, how do you declare a computed property whose getter is async or throws, and what can such a property not have?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Write the effects after get, as in var celsius: Double { get async throws { ... } }, and read it with try await. Such a property (Swift 5.5) must be read-only: no setter, no observers, no key path.

open as a page