I am trying to create a custom setter method for my property. Below is my code.
I am getting a waring Attempting to access 'myProperty' within its own getter
var myProperty:String{
get {
if CONDITION1 {
return CONDITION1_STRING
}else if CONDITION2 {
return CONDITION2_STRING
}else{
return myProperty
}
}
set{
}
}
What is wrong in my code. can any body help to fix this.
First of all quote from Apple Swift Documentation:
The first thing above quote suggesting is that, you can use custom getter and setter of property to get or set values of other property indirectly without exposing it or make it public for others.
If you try to access/get value of property within its own getter than again you are calling getter and loops go infinite. As we know allocation of all this calls are on stack, and stack has limited memory, so once calls stacked at full capacity then it can not handle any more calls and it crash with stackoverflow error.
So, never get or set property's value within its own getter and setter. They are here to provide access to other variables and properties.
Lets expand your code to use
myProperty
With custom getter. I am renaming it here it asmyName
.Here I add two private property
firstName
andlastName
but make itprivate
. But I add another propertymyName
which is public, so i implement custom getter to retrieve name of user based on condition and provide access offirstName
andlastName
indirectly.By same way you can implement custom setter to set value of
firstName
andlastName
of user. But you can not make use of self within its own scope.Create a backing ivar and add a custom setter: