I have a very simple class
class SimpleClass {
var simpleDescription: String {
get {
return self.simpleDescription
}
set {
self.simpleDescription = newValue
}
}
}
What is the correct way to define a default value for the simpleDescription
variable?
Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.
The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created.
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")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With