Search code examples
iosswiftcs193p

How can I make my calculator add a Period in swift?


Here is the code for my UIButton

@IBAction private func performOperation(sender: UIButton) {
    if userIsInTheMiddleOfTyping {
        brain.setOperand(displayValue)
        userIsInTheMiddleOfTyping = false
    }
    if let mathematicalSymbol = sender.currentTitle {
        brain.performOperation(mathematicalSymbol)
    }
    displayValue = brain.result
}

Here is my model or viewcontroller code

private var operations: Dictionary<String,Operation> = [
    "π":    Operation.Constant(M_PI),
    "e":    Operation.Constant(M_E),
    "√":    Operation.UnaryOperation(sqrt),
    "cos":  Operation.UnaryOperation(cos),
    "✕":    Operation.BinaryOperation({ $0 * $1 }),
    "÷":    Operation.BinaryOperation({ $0 / $1 }),
    "+":    Operation.BinaryOperation({ $0 + $1 }),
    "−":    Operation.BinaryOperation({ $0 - $1 }),
    "±":    Operation.UnaryOperation({ -$0 }),
    "=":    Operation.Equals,
    ".":    Operation.Period
]

private enum Operation {
    case Constant(Double)
    case UnaryOperation((Double) -> Double)
    case BinaryOperation((Double, Double) -> Double)
    case Equals
    case Period
}

func performOperation (symbol: String) {
    if let operation = operations[symbol] {
        switch operation {
        case .Constant(let associatedConstantValue):
            accumulator = associatedConstantValue
            break
        case .UnaryOperation(let associatedFunction):
            accumulator = associatedFunction(accumulator)
            break
        case .BinaryOperation(let associatedFunction):
            executePendingBinaryOperation()
            pending = PendingBinaryOperationInfo(binaryFunction: associatedFunction, firstOperand: accumulator)
            break
        case .Equals:
            executePendingBinaryOperation()
            break
        case .Period:
            displayTextContainsPeriod()
            break
        }
    }
}

private func displayTextContainsPeriod() -> Bool
{

}

I know to check if an existing period exists I need to check if the String contains a substring "." but I am not sure how to get the display text in my func displayTextContainsPeriod


Solution

  • You're taking the wrong approach. The . shouldn't be an operator. Your calculator brain should not be involved. This work should be done in your ViewController, not your model. It should operate like the digits and append the . character to the display string if the display doesn't already contain a ..

    You'll want to think about the case when . is entered and the user is not in the middle of typing a number. You might want to start your display with 0. instead of just . for instance.