Browse Questions
- A stored property keeps a value in the instance's memory, while a computed property stores nothing and calculates its value every time it is read.
- intrinsicContentSize is the natural size a view prefers based on its content — like a label fitting its text, or a button fitting its title.
- SOLID is a set of five design guidelines for maintainable OOP code: | Principle | Idea | Swift application | |--|--|--| | Single Responsibility | A type should have one reason to change | Split a…
- The most common causes of memory leaks in iOS are strong reference cycles between classes, closure capture retention, un-invalidated Timers, retained Combine subscriptions, and unmanaged Core…
Answer: A stored property keeps a value in the instance's memory, while a computed property stores nothing and calculates its value every time it is read.
- Stored —
letorvar, part of the instance's layout. Available on structs and classes (not enums). - Computed — always
var, defined by aget(and optionalset). Available on structs, classes, and enums, and can be added in extensions.
Code Example:
struct Rectangle {
// Stored — takes up memory in every Rectangle
var width: Double
var height: Double
// Computed — derived on every access, nothing stored
var area: Double {
width * height
}
}
var rect = Rectangle(width: 4, height: 5)
print(rect.area) // 20.0
rect.width = 10
print(rect.area) // 50.0 — always in sync with its inputs
Key Points:
- Extensions can add computed properties but cannot add stored properties.
- A computed property can never fall out of sync with the values it derives from — that is the main reason to prefer it over caching a derived value in a stored property.
- Callers expect property access to be cheap. If the work is expensive, use a method (
func calculateArea()) or cache the result in alazy/ stored property instead.