Swift has a property declaration syntax very similar to C#'s:
var foo: Int {
get { return getFoo() }
set { setFoo(newValue) }
}
However, it also has willSet
and didSet
actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?
Best Answer
The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is
get
/set
, you need another field to hold the value. WithwillSet
anddidSet
, you can take action when the value is modified without needing another field. For instance, in that example:myProperty
prints its old and new value every time it is modified. With just getters and setters, I would need this instead:So
willSet
anddidSet
represent an economy of a couple of lines, and less noise in the field list.