Using Swift property observers in real apps
Swift property observers let a stored property react when its value changes after initialization. willSet runs before the new value is stored, while didSet runs afterwards and exposes the previous value. Together, they provide a compact way to keep derived state, UIKit views, or persisted preferences in step with a source of truth.
For iOS developers building for Australia, that mechanism can support familiar local details: an order total in Australian dollars, a journey planner for Sydney, Melbourne, or Brisbane, or a reminder that follows the country’s daylight-saving patterns. The language syntax is consistent, but the behaviour still needs to fit the market, devices, and expectations it serves.
The examples below focus on UIKit projects and ordinary Swift values because they make callback timing easy to see. They also show where observers are the wrong tool, especially when work is expensive, state must be rejected rather than repaired, or a framework already provides a better observation model.
Responding at the right moment
A property observer belongs to a stored property and becomes active once initialisation has finished. This matters because observers are not called during initialisation; assigning the initial value should not accidentally trigger a save request, analytics event, or UI update.
final class Basket {
var itemCount = 0 {
willSet {
print("About to store \(newValue) items")
}
didSet {
print("Stored \(itemCount); previously \(oldValue)")
}
}
}
willSet receives the proposed value as newValue, while didSet receives the former value as oldValue. The willSet callback sees the property’s old contents, and the didSet callback sees the new contents. Use didSet for most reactions because the stored state is already consistent when it runs.
Observers can also detect mutations of a value-type property through a mutating method, but they do not turn a property into a broadcast system. A computed property cannot have willSet or didSet; if it needs validation, give it an explicit setter or move the behaviour into a method.
Synchronising UIKit views with model state
In UIKit, a reliable interface usually comes from one source of truth. If a button action, a network callback, and a notification can all modify the same subtotal, an observer can ensure every change reaches the label without repeating rendering code in each path.
final class CheckoutViewController: UIViewController {
@IBOutlet private weak var totalLabel: UILabel!
private var subtotal: Decimal = 0 {
didSet {
renderTotal()
}
}
override func viewDidLoad() {
super.viewDidLoad()
renderTotal()
}
private func renderTotal() {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "AUD"
formatter.locale = Locale(identifier: "en_AU")
totalLabel.text = formatter.string(from: subtotal as NSDecimalNumber)
}
}
The explicit renderTotal() call in viewDidLoad() is necessary because the observer does not run for the initial value. It also gives the screen a predictable first render. Later assignments, wherever they originate, follow the same path.
Keep UI work on the main thread. A property observer executes on the thread that made the assignment, so a model updated by a background task must either schedule the UI refresh with DispatchQueue.main.async or guarantee that all mutations happen on the main actor.
Persisting preferences and app data
Small preference changes are a natural fit for didSet. The observer can write the selected value to UserDefaults, while the rest of the app continues to read the property as the authoritative in-memory value.
enum AppTheme: String {
case system
case light
case dark
}
final class SettingsModel {
var theme: AppTheme = .system {
didSet {
UserDefaults.standard.set(theme.rawValue, forKey: "appTheme")
}
}
}
The choice of data should drive the storage mechanism. A card game might save a sound setting or a chosen ruleset; if your project includes that kind of experience, the three-card poker rules can help identify which values deserve to persist and which should remain temporary. Secrets should not go into UserDefaults, and large records are better handled through a file or database layer.
Restore persisted values explicitly after initialisation, because the observer is silent during setup. Also avoid performing heavy encoding or disk work for every keystroke. Debounce text-driven writes, move expensive I/O away from the callback, and test rapid consecutive changes to make sure the last value wins.
Handling Australian prices, dates and distances
Australia adds useful realism to otherwise abstract examples. Consumer prices normally include the 10% GST, so an Australian storefront often displays $10.00 rather than adding tax at checkout. A model can own the tax-inclusive amount and a didSet observer can refresh the currency label using AUD and the en_AU locale.
Date formatting requires another kind of care. New South Wales and Victoria change their clocks for daylight saving, while Queensland does not. An observer can reformat a selected Date whenever the app assigns it, but it will not run merely because TimeZone.current changed while the app was suspended. Apps that care about this should also handle NSSystemTimeZoneDidChange or UIApplication.significantTimeChangeNotification.
Metric units provide a simpler local check: Australian road and fuel interfaces generally use kilometres and litres. For example, a distance property stored in metres can feed a label that divides by 1,000, while an observer keeps the label aligned after recalculation. The conversion belongs in the presentation layer or a formatter, not as scattered arithmetic inside unrelated actions.
Validating values without hidden surprises
A didSet observer is called after a value has been stored, so it is not a reliable gate for an invalid state. It can detect a problem, restore the previous value with oldValue, and explain the error to the user. This repair pattern works when reverting is harmless.
@IBOutlet private weak var radiusErrorLabel: UILabel!
private var searchRadiusKilometres = 10 {
didSet {
guard 1...100 ~= searchRadiusKilometres else {
searchRadiusKilometres = oldValue
radiusErrorLabel.text = "Enter a radius from 1 to 100 km."
return
}
radiusErrorLabel.text = nil
}
}
Swift does not call the same observer recursively when a value is assigned inside didSet, so restoring oldValue is safe here. If a bad value must never exist—even briefly—or the operation has side effects such as a network request, validate before assignment inside a method and make direct external assignment unavailable.
Optional values behave as expected: assigning a city or a selected filter from nil to a value, or from a value back to nil, invokes the observer. Computed properties still cannot use these callbacks. For those, centralise updates in an explicit method or a custom setter, and avoid storing the same fact in two properties that can drift apart.
Selecting the right observation model
Plain observers are a good fit for local, deterministic reactions: update a label, mirror a setting, or record a lightweight event. Combine’s @Published is useful when other objects need a publisher; it emits before the wrapped property is updated, which is different from didSet. The Observation framework’s @Observable suits SwiftUI-facing state, while key-value observing remains relevant for NSObject-based code and Objective-C interoperability.
Choose based on scope, lifecycle, and who consumes the change. A private UI property does not need a framework-level abstraction, while shared application state benefits from a designed publisher or observable model. Business workflows that trigger several coordinated actions are often clearer as explicit methods, with observers limited to presentation and simple persistence.
- Use
didSetwhen the reaction needs the updated property value. - Use
willSetonly when the pre-change state provides genuine value. - Keep observers small, deterministic, and free of long-running work.
- Treat initialisation separately because observers do not run for initial values.
- Maintain one source of truth instead of mirroring state without a defined owner.
- Select
@Published,@Observable, KVO, or explicit methods according to consumers and lifecycle.
A practical dividing line is to keep policy in the model and reactions near the state they affect. That makes the callback easy to test and prevents a presentation detail from quietly becoming the owner of business logic. Observers then remain a focused Swift mechanism rather than a substitute for application architecture.
In your current UIKit project, add one didSet observer to a stored property, change that property from a button action, and inspect the printed values in Xcode’s console.