-1

I understand how to use didSet and willSet for variables but not really why. When should I use these methods and why?

Usually when you update a value you have some kind of button for example where you update a textField and then set a variables value to the textFields for example. If I want to pass something to another viewController or I do it in the button action.

So my question is:
When and why should I use didSet and willSet for my variables?

0

2 Answers 2

1

Sometimes you want to observe the value change of a variable. And that's when didSet and willSet are useful.

didSet is called after the value changes, and you can use it to notify some Manager about it or do whatever you need.

willSet is sometimes used to modify the value before it is given to the variable. For example, you receive a String which is a timestamp from the server, and you want to transform it into a readable date text.

1

When you need to observe value change for variable you need to user didset/willset of variable.

willSet -- is called just before the value is stored. didSet -- is called immediately after the new value is stored.

refer below link for more details