Search code examples
iosswiftcalculatorrpn

Swift differentiate Clear (C) and All clear (AC)


Hello I am a beginner and I am building a RPN calculator. all my operations are effectuated in a separated viewcontroller called calcengine. I have some code for the AC and I have two questions:

 @IBAction func AllClear(sender: UIButton) {
    userHasStartedTyping = false
    labelDisplay.text = "\(0)"
    self.calcEngine!.operandStack.removeAll()  
}

Here is the code for the calculations in the viewcontroller:

@IBAction func operation(sender: UIButton) {
    let operation = sender.currentTitle!
    if userHasStartedTyping { 
        Enter()  
    }
    self.displayValue = (self.calcEngine?.operate(operation))!
    Enter() 
}

and the code for calculations in the calcengine:

class CalculatorEngine: NSObject   
{ 
var operandStack = Array<Double>() //array

func updateStackWithValue(value: Double)
{ self.operandStack.append(value) }

func operate(operation: String) ->Double
{ switch operation

{

case "×":
    if operandStack.count >= 2 {
        return self.operandStack.removeLast() *         self.operandStack.removeLast()
    }


case "÷":
    if operandStack.count >= 2 {
        return self.operandStack.removeFirst() / self.operandStack.removeLast()
    }


case "+":
    if operandStack.count >= 2 {
        return self.operandStack.removeLast() + self.operandStack.removeLast()
    }


case "−":
    if operandStack.count >= 2 {
        return self.operandStack.removeFirst() -      self.operandStack.removeLast()
    }

    default:break
    }
    return 0.0
}
}
  1. Is this code right to clear all the calculation that have been done.
  2. How could I differentiate this one from the Clear function and build code for the clear?

Solution

  • A typical "Clear" button on a calculator only clears the user entered number. In your case this would be similar to AllClear() but without emptying you RPN stack:

    @IBAction func Clear(sender: UIButton) 
    {
        userHasStartedTyping = false
        labelDisplay.text = "\(0)"
    }