swift - can we use willset and didset with getter and setter -


i reading willset , didset of properties in swift came know can use these variable having initial value below:

var property = "name" {     willset     {         print("property changed")     }     didset     {         if property == oldvalue         {             print("values same")         }         else         {             print("value changed")         }     } }  property = "anothername" 

so can use willget , didset below:

var property2:string{      willset     {         print("value change")     }     didset     {         print("value changes")     } } 

it gives me error:

non-member observing properties require initializer var property2:string{     ^ 

so can explain me going on here , can use getter , setter willset , didset like:

var property2:string{      get{return property2}     set{propert2 = newvalue}      willset     {         print("value change")     }     didset     {         print("value changes")     } } 

the error says lack initializer can solved giving property default value first piece of code did:

var property2:string = "some default value"{      willset     {         print("value change")     }     didset     {         print("value changes")     } } 

now answer why can't use property observers on computed properties.

because there no point.

for settable computed property, have setter, can write whatever code want execute when value set in setter. why need willset or didset? , get-only computed property, can't set when expect willset , didset executed?

basically, set block in computed properties fulfils purpose of willset , didset. write in willset can write in set before set value. write in didset can write in set after set value.

also, note third code can cause stack overflow since accessing property2 inside own getter , setting inside own setter.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -