Add an Undo button to your Calculator. In Assignment 1’s Extra Credit, you might have added a “backspace” button. Here we’re talking about combining both backspace and actual undo into a single button. If the user is in the middle of entering a number, this Undo button should be backspace. When the user is not in the middle of entering a number, it should undo the last thing that was done in the CalculatorBrain. Do not undo the storing of M’s value (but DO undo the setting of a variable as an operand).
Rename the backspace button in the storyboard:
In the calculator brain add a new method removing the last item in the stack – if there is any:
mutating func undo() { if !stack.isEmpty { stack.removeLast() } }
In the view controller change the name of the backspace action – this will break your code, but that’s the fun – you will need to rewire the undo buttons. The backspace part stays untouched. When the user is not in the middle of typing call the undo method of the calculator brain and update the display:
@IBAction func undo(_ sender: UIButton) { if userIsInTheMiddleOfTyping, var text = display.text { ... } else { brain.undo() displayResult() } }
The complete code for the assignment #2 task #10 is available on GitHub.