properties - Is there a way to override "property" setters and getters in Swift? -


after reading @property/@synthesize equivalent in swift, became curious how functionality objective c retained.

say have following in objective c:

@interface myclass @property (readwrite) mytype *myvar; @end 

this can accessed such dot- , smalltalk-based syntaxes:

type *newvar1 = myclassinstance.myvar; type *newvar2 = [myclassinstance myvar];  myclassinstance.myvar = newvar1; [myclassinstance setmyvar: newvar2]; 

and if want add additional functionality getters/setters, can this:

@implementation myclass  - (mytype *) myvar {     // more stuff     return self._myvar; }  - (void) setmyvar: (mytype *) newvar {     self._myvar = newvar;     // more stuff }  @end 

(see custom setter @property?)

however, the accepted answer above linked question says swift doesn't differentiate between properties , instance variable. so, have following in swift:

class myclass {     var myvar: mytype } 

as far know, way access myvar such:

var newvar1 = myclassinstance.myvar;  myclassinstance.myvar = newvar1; 

but don't know how customize these getters , setters. is there swift equivalent of objective c @property overrides?

while researching question, happened upon answer, still figured should put here else same question.


yes, according the swift programming language documentation's page on properties, getters , setters can made in similar way how c# tackles problem:

class myclass {     var myplainvar: mytype = mytype()      var mycustomgettervar: mytype {         // more stuff         return self.mycustomgettervar     }      var mycustomgettersettervar: mytype {         {             // more stuff             return self.mycustomgettersettervar         }         set {             // stuff             self.mycustomgettersettervar = newvalue             // more stuff         }     }      var mycustomfancyvar: mytype! {         willset {             // stuff newvalue         }         // actual setting done automatically, no set{}         didset {             // more stuff oldvalue         }     } } 

note variables didset must initialized or explicitly unwrapped (using !), , cannot have get reason.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -