What is the purpose of willSet and didSet in Swift? -
swift has property declaration syntax similar c#'s:
var foo: int { { return getfoo() } set { setfoo(newvalue) } }
however, has willset
, didset
actions. these called before , after setter called, respectively. purpose, considering have same code inside setter?
the point seems sometimes, need property has automatic storage and behavior, instance notify other objects property changed. when have get
/set
, need field hold value. willset
, didset
, can take action when value modified without needing field. instance, in example:
class foo { var myproperty: int = 0 { didset { print("the value of myproperty changed \(oldvalue) \(myproperty)") } } }
myproperty
prints old , new value every time modified. getters , setters, need instead:
class foo { var mypropertyvalue: int = 0 var myproperty: int { { return mypropertyvalue } set { print("the value of myproperty changed \(mypropertyvalue) \(newvalue)") mypropertyvalue = newvalue } } }
so willset
, didset
represent economy of couple of lines, , less noise in field list.
Comments
Post a Comment