Avatar ·

What are willSet and didSet for in Swift? Property Observers

Hello everyone! I recently started learning Swift and came across something called `willSet` and `didSet`. I kind of understand that it's related to property changes, but I can't fully grasp why they are needed at all.\n\nFor example, I have a simple app where I want the label on the screen to update whenever the value of the `score` variable changes. Currently, I do it like this:\n\n```swift\nvar score = 0 {\n willSet {\n print("A new value is coming soon: \\(newValue)")\n }\n didSet {\n print("The old value was: \\(oldValue)")\n scoreLabel.text = "Score: \\(score)"\n }\n}\n```\n\nI see that the code works, but I don't understand the difference from a simple method like `updateScore(newValue: Int)` that I call manually. What's the benefit? When do you actually need to use `willSet` and `didSet`?