Properties in Swift: Computed, Observers, lazy, static and Property Wrappers
Computed Properties
swift
struct Circle {
var radius: Double
var diameter: Double {
get { radius * 2 }
set { radius = newValue / 2 }
}
var area: Double { 3.14159 * radius * radius } // read-only
}
var c = Circle(radius: 5)
c.diameter = 20
print(c.radius, c.diameter, c.area)
Output
10.0 20.0 314.159
Property Observers
swift
class Thermostat {
var target = 20 {
willSet { print("will change to", newValue) }
didSet { print("changed from", oldValue, "to", target) }
}
}
let t = Thermostat()
t.target = 24
Output
will change to 24 | changed from 20 to 24
lazy Properties
A lazy property is created the first time you use it. It is useful for expensive work that may never be needed.
swift
class Report {
lazy var data: [Int] = {
print("loading data...")
return Array(1...5)
}()
}
let r = Report()
print("report created")
print(r.data.count)
print(r.data.count)
Output
report created | loading data... | 5 | 5
Static Properties
swift
struct Config {
static let appName = "Demo"
static var launchCount = 0
}
Config.launchCount += 1
print(Config.appName, Config.launchCount)
Output
Demo 1
Property Wrappers
A property wrapper packages repeated logic for a property. SwiftUI's @State and @Binding are property wrappers.
swift
@propertyWrapper
struct Clamped {
private var value: Int
let range: ClosedRange<Int>
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
}
struct Player {
@Clamped(0...100) var health = 50
}
var p = Player()
p.health = 150
print(p.health)
p.health = -20
print(p.health)
Output
100 | 0
Common Mistakes
- Doing slow work inside a computed property that is read often
- Triggering observers inside
init, where they do not run - Using
lazyon alet - Overusing wrappers for tiny logic
Practice
- Add a
didSetthat prints when a score passes 100 - Write a
@Trimmedwrapper for Strings - Make a lazy property that loads a big array
Conclusion
Computed, observed, lazy and wrapped properties let you control values without cluttering your code.
Quick Summary: Computed; observers; lazy; static; wrappers.

