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.
fileprivate var myPrivateProperty: String = "") and you can return that rather thanreturn myPrivateProperty, and in the setter you need to assign the new value to it, like e.g.myPrivateProperty = newValueand job's done.