Set a default value for a property with defined getter and setter
In Swift, getters and setters are used for computed properties - there is no storage for the property and thus, in your case, simpleDescription
can't be set in a setter.
If you need a default value, use:
class SimpleClass {
var simpleDescription: String = "default description"
}
if you want to initialize use:
class SimpleClass {
var simpleDescription: String
init (desc: String) {
simpleDescription = desc
}
}
If what you want is to perform an action each time a variable is set or just to check if the value is correct you can use Property Observers
From docs:
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
You can use them like this:
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
EDIT
Looks like this doesn't work when overriding inherited properties. Here is an example of what you can't do:
class StepWihtoutCounter {
var totalSteps: Int = 0
}
class StepCounter: StepWihtoutCounter {
override var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}