Reputation: 2307
As an introductory to Swift programming i'm trying to make a small calculator app. I am getting a bug when trying to create the plus-minus button function. The purpose of the button is when clicked, if the value of the display text is > 0
a minus symbol is added at the beginning of the string (i.e. 8 ---> -8
, and if the value of the display text is < 0
the value of the display text is multiplied by minus 1 and the display text value is assigned as a string of the new number.
My issue is that when I click the minus button the first time it works as expected, however, when I click it the second time (< 0
) the display text still keeps the minus symbol before the number. My code is:
@IBAction func pmButton(_ sender: Any) {
if toFloat(value: display.text!) < 0 {
display.text = NSNumber(value: (toFloat(value: display.text!) * -1)).stringValue
print(display.text!)
}
if toFloat(value: display.text!) > 0 {
display.text = "-" + display.text!
}
}
The value of print(display.text!)
gives the correct value (no minus symbol) but on the actual label the minus symbol persists. This is even the case when I add some erroneous value to the string i.e.
display.text = NSNumber(value: (toFloat(value: display.text!) * -1)).stringValue + "abc"
would result in (-8 ---> -8abc
).
I also tried adding print(display.text!)
before I reassign the value (on line 4) and it reverts back to the original minus value. So it seems like display.text
gets assigned in the function but never properly updates outside of the function.
I'm sure it's something super simple but can't seem to work it out.
Upvotes: 0
Views: 213
Reputation: 6075
In your first if
block you change the value of display.text
so that the second if
condition is met as well; just use else if
to only run one of the blocks.
Upvotes: 2