software is fun software is fun - 2 years ago 102
iOS Question

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 {
userIsInTheMiddleOfTyping = false
if let mathematicalSymbol = sender.currentTitle {
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
case .UnaryOperation(let associatedFunction):
accumulator = associatedFunction(accumulator)
case .BinaryOperation(let associatedFunction):
pending = PendingBinaryOperationInfo(binaryFunction: associatedFunction, firstOperand: accumulator)
case .Equals:
case .Period:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download