Why do we need to use setters in the particular case below in Swift.
I'm trying to convert 'display.text' String
to Double
. I understand that getter brings back String
value and converts it to Double
and assigns this value to variable newValue
.
Question: why we set display.text value back into String
again using = "\(newValue)"
if we just converted it into Double
?
var doubleValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
}
}
I understand that getter brings back String value and converts it to Double and assigns this value to variable newValue.
This isn't correct. The getter just returns the double. There is no newValue
in the getter.
In the setter, newValue
is a shortcut for "the implied argument of the setter." The explicit syntax is this:
var doubleValue: Double {
...
set(newValue) {
display.text = "\(newValue)"
}
}