Project 2: Calculator App with an Expression Parser

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 13 min read · Updated

Text to answer

  1. The user types the expression with the keypad.
  2. The tokeniser cuts it into numbers and operators.
  3. The first pass multiplies and divides: 3 * 4 becomes 12.
  4. The second pass adds and subtracts: 2 + 12 is 14.

A calculator looks like the easiest app there is, which makes it a good first project after the Expense Tracker. The screen is simple, but the logic is real: you must turn the text "2+3*4" into 14, not 20. Many beginners reach for a library. Here you write a small parser yourself, so you learn how text becomes a result, and you keep it in a plain Swift type that you can test without launching the Simulator.

The screen is a grid of buttons, a display for the expression and a line for the result or an error. The state lives in an @Observable model, the same pattern as lesson 13, so the view only describes what to show.

Concepts in this project

  • Tokenising: splitting "12+3.5*2" into numbers and operators. A minus at the very start belongs to the first number.
  • Order of operations: pass one handles * and /, pass two handles + and -. This matches mathematics.
  • Failing safely: evaluate returns an optional. A nil means invalid input, and the screen shows a message instead of crashing.
  • Separating logic from UI: Calculator is an enum with static functions and no SwiftUI import, so tests call it directly.
  • Button grids: ForEach over rows of labels, frame(maxWidth: .infinity) so keys share the width.
  • Swift Testing: @Test functions with #expect, one small fact per test.

Create the project

  1. In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product PrimeCalc.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
PrimeCalc/
  CalculatorApp.swift     @main
  Calculator.swift        tokenise and evaluate
  CalculatorModel.swift   expression, result, error
  CalculatorView.swift    display and keypad
PrimeCalcTests/
  CalculatorTests.swift

The code

`Calculator.swift`

import Foundation

enum Calculator {
    private enum Token {
        case number(Double)
        case op(Character)
    }

    // Cuts "12+3.5*2" into numbers and operators. A leading minus belongs to the first number.
    private static func tokens(_ text: String) -> [Token]? {
        var result: [Token] = []
        var current = ""
        for ch in text where ch != " " {
            if ch.isNumber || ch == "." {
                current.append(ch)
            } else if "+-*/".contains(ch) {
                if current.isEmpty {
                    if ch == "-" && result.isEmpty {
                        current = "-"
                        continue
                    }
                    return nil
                }
                guard let value = Double(current) else { return nil }
                result.append(.number(value))
                result.append(.op(ch))
                current = ""
            } else {
                return nil
            }
        }
        guard let last = Double(current) else { return nil }
        result.append(.number(last))
        return result
    }

    // Returns nil for anything that is not a valid sum, including division by zero.
    static func evaluate(_ text: String) -> Double? {
        guard let items = tokens(text), items.count % 2 == 1 else { return nil }
        guard case .number(let first) = items[0] else { return nil }

        // Pass 1: do * and / now, keep + and - for later.
        var numbers: [Double] = [first]
        var pending: [Character] = []
        var index = 1
        while index < items.count {
            guard case .op(let symbol) = items[index],
                  case .number(let value) = items[index + 1] else { return nil }
            switch symbol {
            case "*":
                numbers[numbers.count - 1] *= value
            case "/":
                if value == 0 { return nil }
                numbers[numbers.count - 1] /= value
            default:
                pending.append(symbol)
                numbers.append(value)
            }
            index += 2
        }

        // Pass 2: + and - from left to right.
        var total = numbers[0]
        for (position, symbol) in pending.enumerated() {
            let next = numbers[position + 1]
            total = symbol == "+" ? total + next : total - next
        }
        return total
    }

    // 14.0 prints as 14, 3.75 stays 3.75.
    static func format(_ value: Double) -> String {
        if value == value.rounded() && abs(value) < 1e15 {
            return String(Int(value))
        }
        return String(format: "%.6g", value)
    }
}

`CalculatorModel.swift`

import Observation

@Observable
final class CalculatorModel {
    var expression = ""
    var result = ""
    var hasError = false

    func press(_ key: String) {
        switch key {
        case "C":
            expression = ""
            result = ""
            hasError = false
        case "⌫":
            if !expression.isEmpty { expression.removeLast() }
        case "=":
            if let value = Calculator.evaluate(expression) {
                result = Calculator.format(value)
                expression = result
                hasError = false
            } else {
                result = "Invalid expression"
                hasError = true
            }
        default:
            hasError = false
            result = ""
            expression += key
        }
    }
}

`CalculatorView.swift`

import SwiftUI

struct CalculatorView: View {
    @State private var model = CalculatorModel()

    private let rows: [[String]] = [
        ["7", "8", "9", "/"],
        ["4", "5", "6", "*"],
        ["1", "2", "3", "-"],
        [".", "0", "=", "+"],
        ["C", "⌫"]
    ]

    var body: some View {
        VStack(spacing: 12) {
            Spacer()
            Text(model.expression.isEmpty ? "0" : model.expression)
                .font(.system(size: 44, weight: .light))
                .lineLimit(1)
                .minimumScaleFactor(0.4)
                .frame(maxWidth: .infinity, alignment: .trailing)
            Text(model.result)
                .font(.title3)
                .foregroundStyle(model.hasError ? Color.red : Color.secondary)
                .frame(maxWidth: .infinity, alignment: .trailing)
                .frame(height: 28)

            ForEach(rows, id: \.self) { row in
                HStack(spacing: 12) {
                    ForEach(row, id: \.self) { key in
                        Button {
                            model.press(key)
                        } label: {
                            Text(key)
                                .font(.title)
                                .frame(maxWidth: .infinity, minHeight: 64)
                        }
                        .buttonStyle(.borderedProminent)
                        .tint(color(for: key))
                    }
                }
            }
        }
        .padding()
    }

    private func color(for key: String) -> Color {
        if "+-*/=".contains(key) { return .orange }
        if key == "C" || key == "⌫" { return .gray }
        return .blue
    }
}

#Preview {
    CalculatorView()
}

`CalculatorApp.swift`

import SwiftUI

@main
struct CalculatorApp: App {
    var body: some Scene {
        WindowGroup {
            CalculatorView()
        }
    }
}

`CalculatorTests.swift (in the tests target)`

import Testing
@testable import PrimeCalc

struct CalculatorTests {
    @Test func multiplicationComesBeforeAddition() {
        #expect(Calculator.evaluate("2+3*4") == 14)
    }

    @Test func decimalsAndDivision() {
        #expect(Calculator.evaluate("7.5/2") == 3.75)
    }

    @Test func leadingMinus() {
        #expect(Calculator.evaluate("-5+2") == -3)
    }

    @Test func divisionByZeroIsInvalid() {
        #expect(Calculator.evaluate("5/0") == nil)
    }

    @Test func brokenInputIsInvalid() {
        #expect(Calculator.evaluate("2++3") == nil)
        #expect(Calculator.evaluate("abc") == nil)
        #expect(Calculator.evaluate("") == nil)
    }

    @Test func formatDropsTrailingZero() {
        #expect(Calculator.format(14) == "14")
        #expect(Calculator.format(3.75) == "3.75")
    }
}

Walkthrough

Start with tokens. It walks through the text one character at a time and builds a number in a string called current. When it meets an operator it converts that string to a Double, stores it, then stores the operator. Spaces are skipped, and any other character makes the function return nil, so letters cannot get through. The special case is the minus sign: when current is empty and nothing has been stored yet, the minus is the start of a negative number, so it becomes the first character of current.

evaluate then reads the tokens in pairs: an operator followed by a number. For * and / it changes the last number in the list straight away, which is how multiplication gets done before addition. For + and - it saves the operator and the next number for the second pass. Division by zero returns nil. The second pass is a plain loop that adds or subtracts from left to right.

CalculatorModel is tiny on purpose. press handles five kinds of key: clear, backspace, equals, and everything else, which is appended to the expression. After a successful equals the expression becomes the result, so you can keep calculating. The model never draws anything, so you could reuse it in a Mac or watch app.

In the view, rows is an array of arrays of strings. Two nested ForEach loops build the grid. id: \.self is fine here because every label is unique. The colour function gives operators orange and the clear keys grey, which is a small touch that makes the keypad easier to read.

How it works

  • A key calls model.press(key). The model changes expression or result, and SwiftUI redraws because the model is @Observable.
  • evaluate tokenises, runs the multiplication and division pass, then the addition and subtraction pass.
  • Any unexpected input returns nil, and the model sets hasError so the result line turns red.
  • format prints 14.0 as 14 and keeps 3.75 as it is.

Expected output

The screen shows 0 and the keypad. Press 2, +, 3, *, 4, =: the display shows 14. Press C, then 7, ., 5, /, 2, =: the display shows 3.75. Press 5, /, 0, =: the line under the display shows "Invalid expression" in red and the app keeps running. Press the backspace key to remove the last character. In the tests target, all six tests pass when you press Command+U.

Your task

  1. Build the app and run each example above.
  2. Run the tests with Command+U.
  3. Add a percent key that divides the last number by 100.
  4. Add brackets by letting evaluate call itself on the text inside them.

How to check it worked

  • 2+3*4 gives 14.
  • Division by zero shows a message and does not crash.
  • You can explain why the evaluator uses two passes.

Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.

Frequently asked questions

Why not use NSExpression?

It can crash on bad input, and it hides how parsing works. Writing a small parser is safer and teaches you how text becomes a result.

Why return nil instead of throwing an error?

Bad input is normal in a calculator. An optional is simple and the caller must handle it. For richer messages you could throw a custom Error instead.

Is Double fine for money?

Not for real money. Use whole cents in an Int or Decimal, as the Expense Tracker and the shop project do.