I'm using this variable
public var tick: Int64 {
get {
return UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0
}
set(v) {
let cur = UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0 + v
UserDefaults.standard.set(cur, forKey: TICK)
}
}
But I want to know, that is the proper way to call getter in inside setter? I mean:
set(v) {
let cur = /*HOW TO CALL GETTER HERE? */ + v
UserDefaults.standard.set(cur, forKey: TICK)
}
if I use self
instead of /*HOW TO CALL GETTER HERE? */
, it doesn't work.
Getters and setters are essential in any language. Here, in Swift, they are applied to computed properties that do not have access to their own storage, so need to be derived from other properties.
A getter method is used to perform a computation when requested. A setter method is an optional method. It can be used to modify a related property.
Setting a private setter only works with properties marked as var and not let because properties marked with let are constants and by nature they are immutable. This Swift feature could also be used in cases when we have a read-only property backed by another private property.
You can simply call the value (tick
) within its setter to get the old value:
public var tick: Int64 {
get {
return UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0
}
set(v) {
let cur = tick + v
UserDefaults.standard.set(cur, forKey: TICK)
}
}
A standard implementation of a computed variable with getter and setter is as follows:
private var stored: String
public var computed: String {
get {
return stored
}
set {
stored = newValue
}
}
The name newValue
in a setter definition represents the value which is being applied.
You could throw the following into a playground to see:
struct SomeStruct {
private var stored: String = ""
public var computed: String {
get {
return self.stored
}
set {
self.stored = newValue
}
}
}
var value = SomeStruct()
print(value.computed)
value.computed = "new string"
print(value.computed)
If you really wanted to reference the getter in your setter definition, you could. Perhaps you would want to only apply the newValue
in the setter based on some kind of condition of the getter:
public var computed: String {
get {
return self.stored
}
set {
self.stored = self.computed == "" ? self.computed : newValue
}
}
This is also valid and should be able to fit your requirements.
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