0
0
Swiftprogramming~3 mins

Why Property observers (willSet, didSet) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could automatically notice and react to changes without you writing extra code every time?

The Scenario

Imagine you have a simple app that tracks a user's score. Every time the score changes, you want to update the screen and maybe save the new score. Without property observers, you have to remember to add extra code everywhere you change the score.

The Problem

This manual way is slow and easy to forget. If you miss updating the screen or saving the score in one place, your app shows wrong info or loses data. It's like having to remember to turn off every light in a big house manually -- easy to miss one!

The Solution

Property observers like willSet and didSet let you watch a property for changes in one place. You write the update code once, and it runs automatically whenever the property changes. This keeps your code clean and reliable.

Before vs After
Before
score = 10
updateScreen()
saveScore()
After
var score: Int = 0 {
  willSet { print("Score will change to \(newValue)") }
  didSet { updateScreen(); saveScore() }
}
What It Enables

This lets you react instantly and safely to changes, making your app smarter and easier to maintain.

Real Life Example

Think of a fitness app that updates your daily step count. With property observers, the app can automatically refresh the display and sync data whenever your step count changes, without extra code everywhere.

Key Takeaways

Manually tracking changes is error-prone and repetitive.

Property observers centralize change handling in one place.

They make your code cleaner, safer, and easier to update.