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.
Create a backing ivar and add a custom setter:
private _myProperty: String
var myProperty: String {
get {
if CONDITION1 {
return CONDITION1_STRING
} else if CONDITION2 {
return CONDITION2_STRING
} else {
return _myProperty
}
}
set {
_myProperty = newValue
}
}
First of all quote from Apple Swift Documentation:
Computed Properties
In addition to stored properties, classes, structures, and
enumerations can define computed properties, which do not actually
store a value. Instead, they provide a getter and an optional setter
to retrieve and set other properties and values indirectly.
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 as myName
.
private var firstName : String = ""
private var lastName : String = ""
var myName:String{
get {
if CONDITION1 {
return firstName
}else if CONDITION2 {
return lastName
}else{
return firstName + lastName
}
}
}
Here I add two private property firstName
and lastName
but make it private
. But I add another property myName
which is public, so i implement custom getter to retrieve name of user based on condition and provide access of firstName
and lastName
indirectly.
By same way you can implement custom setter to set value of firstName
and lastName
of user.
But you can not make use of self within its own scope.