Swift Properties
Properties attach values to a struct, class or enum. Swift has several flavours: some store a value, some calculate it on demand, some react when they change, and some wait until they are first used. Knowing which to pick keeps your types small and correct.
| Kind | Stores a value? | Example |
|---|---|---|
| Stored property | Yes | var name: String |
| Computed property | No — calculated each time | var area: Double { width * height } |
| Property observer | Stored + code that runs on change | var score = 0 { didSet { … } } |
| Lazy stored property | Yes, created on first access | lazy var cache = … |
| Type (static) property | One value shared by the type | static let maxPlayers = 4 |
Stored properties
A stored property is a constant (let) or variable (var) that is part of each instance. You have used them in every struct and class so far.
Computed properties
A computed property has no storage of its own. It provides a getter — and optionally a setter — that compute a value from other properties.
struct Rectangle {
var width: Double
var height: Double
// read-only computed property: just return the value
var area: Double {
width * height
}
// read-write computed property
var square: Bool {
get { width == height }
set {
if newValue { height = width }
}
}
}
var r = Rectangle(width: 4, height: 3)
print("Area:", r.area)
print("Square?", r.square)
r.square = true // runs the setter
print("Now \(r.width) x \(r.height), area \(r.area)")Area: 12.0
Square? false
Now 4.0 x 4.0, area 16.0
Inside set, the new value is available as newValue (you may also name it: set(makeSquare) { … }).
Note: Computed properties must always be declared with
var, even read-only ones, because their value can change.
Property observers: willSet and didSet
Observers let a stored property run code whenever it is assigned. willSet runs just before the change (with newValue), didSet runs just after (with oldValue).
struct Thermostat {
var target: Int = 20 {
willSet {
print("Changing from \(target) to \(newValue)…")
}
didSet {
if target > 28 {
print("Too hot! Limiting to 28.")
target = 28 // assigning here does not re-trigger the observers
}
}
}
}
var home = Thermostat()
home.target = 23
home.target = 35
print("Final target:", home.target)Changing from 20 to 23…
Changing from 23 to 35…
Too hot! Limiting to 28.
Final target: 28
Observers are perfect for validation, logging, or keeping another value in sync. They do not run during the instance's own initializer.
Lazy stored properties
A lazy var is not computed when the instance is created — only the first time someone reads it. That is useful for expensive setup that might never be needed.
struct Report {
let rows: [Int]
lazy var total: Int = {
print("(computing total…)")
return rows.reduce(0, +)
}()
}
var report = Report(rows: [12, 30, 8])
print("Report created")
print("Total:", report.total)
print("Total again:", report.total) // stored now, no recomputationReport created
(computing total…)
Total: 50
Total again: 50
A lazy property must be a var, and because reading it may store a value, you can only use it on a var struct instance.
Type properties with static
A type property belongs to the type itself, not to any one instance. There is exactly one copy, shared by everybody.
struct Player {
static let maxLevel = 50
static var created = 0
let name: String
var level = 1 {
didSet { level = min(level, Player.maxLevel) }
}
init(name: String) {
self.name = name
Player.created += 1
}
}
var p1 = Player(name: "Kai")
let p2 = Player(name: "Lan")
p1.level = 99
print(p1.name, "level", p1.level)
print(p2.name, "level", p2.level)
print("Players created:", Player.created)Kai level 50
Lan level 1
Players created: 2
You access type properties through the type name: Player.maxLevel. In classes you can also write class var for a computed type property that subclasses may override.
Tip: Prefer a computed property over a stored one whenever the value can be derived from others. A stored copy can drift out of sync; a computed one never does.
Test yourself
Inside a didSet observer, which name holds the previous value?
newValueoldValuepreviousself.old
When is a lazy var initial value computed?
- When the program starts
- When the instance is created
- The first time the property is read
- Every time it is read
How do you read a static let maxLevel declared in struct Player?
player.maxLevelPlayer.maxLevelself.maxLevelfrom outsidestatic.maxLevel