In Swift, what is the difference between a stored property and a computed property, and how is a read-only computed property declared?
answer
- memory versus code
- get and set accessors
- the setter's implicit parameter name
- getter only, still var
basics
~20 sA 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 sA **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 linesstruct 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) // truego deeper
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.
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.
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.
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.