var userState: UserState {
get {
return userState
}
set {
print("\(self.userState)")
}
}
Returning userState causes an infinite loop. I'm not interested in the getter method and just want to return the value of the property in the getter. I would rather like to customise the setter method.
If you would like to override a setter, but keep your property readable, then you need to make a variable to "back" the property:
private var storedUserState: UserState
var userState: UserState {
get {
return storedUserState
}
set {
print("Before: \(self.storedUserState)")
storedUserState = newValue
print("After: \(self.storedUserState)")
}
}
If you would like to customize a setter method, but would prefer the property to remain stored, use property observers instead of overriding the accessors:
var userState: UserState = nil {
willSet(newState) {
print("About to set userState: \(newState)")
}
didSet {
print("Finished: new=\(userState), old=\(oldValue)")
}
}
Instead of set
, what you want is willSet
or didSet
, which get run before/after the value changes. Then you can omit get
.
With willSet
, since the variable hasn't changed yet, the new value is available in a parameter called newValue
. Conversely, didSet
has oldValue
.
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