calculator in swift

Interactive Calculator Demo

Use this mini calculator to test the same arithmetic logic you would implement in a Swift app.

Result will appear here.

How to Build a Calculator in Swift (Step-by-Step)

Building a calculator in Swift is one of the best beginner-to-intermediate iOS projects. It teaches user input handling, state management, data validation, edge-case logic, and clean app architecture. Even though a calculator looks simple on the surface, writing one well is a great exercise in professional coding habits.

In this guide, you will learn how to structure calculator logic, connect it to an interface in SwiftUI or UIKit, and avoid common mistakes such as divide-by-zero crashes and floating-point formatting glitches.

1) Start with the Calculator Engine

Before touching buttons and layout, define the math engine. Keeping logic separated from UI is a key software engineering principle. You can then test the engine independently and reuse it across iPhone, iPad, or even macOS versions of your app.

Example Swift Model

enum Operation {
    case add, subtract, multiply, divide
}

struct CalculatorEngine {
    func calculate(_ a: Double, _ b: Double, operation: Operation) -> Result<Double, String> {
        switch operation {
        case .add:
            return .success(a + b)
        case .subtract:
            return .success(a - b)
        case .multiply:
            return .success(a * b)
        case .divide:
            guard b != 0 else { return .failure("Cannot divide by zero.") }
            return .success(a / b)
        }
    }
}

Notice the use of Result<Double, String>. This is cleaner than returning optional values because it clearly tells the UI whether it got a valid number or an error message.

2) Build the Interface in SwiftUI

SwiftUI makes calculator UI development fast because state changes are automatically reflected on screen. You can store user inputs in @State properties and compute output when the button is tapped.

Simple SwiftUI Calculator View

import SwiftUI

struct CalculatorView: View {
    @State private var first = ""
    @State private var second = ""
    @State private var resultText = "Result will appear here."
    @State private var selectedOp: Operation = .add

    private let engine = CalculatorEngine()

    var body: some View {
        VStack(spacing: 12) {
            TextField("First number", text: $first)
                .textFieldStyle(.roundedBorder)
                .keyboardType(.decimalPad)

            Picker("Operation", selection: $selectedOp) {
                Text("+").tag(Operation.add)
                Text("-").tag(Operation.subtract)
                Text("×").tag(Operation.multiply)
                Text("÷").tag(Operation.divide)
            }
            .pickerStyle(.segmented)

            TextField("Second number", text: $second)
                .textFieldStyle(.roundedBorder)
                .keyboardType(.decimalPad)

            Button("Calculate") {
                guard let a = Double(first), let b = Double(second) else {
                    resultText = "Please enter valid numbers."
                    return
                }

                switch engine.calculate(a, b, operation: selectedOp) {
                case .success(let value):
                    resultText = "Result: \\(value)"
                case .failure(let message):
                    resultText = message
                }
            }

            Text(resultText)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding()
                .background(Color.blue.opacity(0.08))
                .cornerRadius(8)
        }
        .padding()
    }
}

3) UIKit Version (If You Prefer Storyboards)

UIKit remains important for legacy apps and teams with storyboard-based workflows. The architecture is similar: UI controls collect input, controller calls model, controller updates labels.

  • Create two UITextField inputs for numbers.
  • Add a UISegmentedControl for operation selection.
  • Use a UIButton to trigger calculation.
  • Display output in a UILabel.

Even in UIKit, keep calculation logic in a separate Swift file. Avoid writing raw math logic directly inside your view controller whenever possible.

4) Handle Edge Cases Like a Pro

Many beginner calculator projects fail in edge cases. A polished app should handle messy user behavior gracefully.

  • Empty input: Show an error like “Please enter both numbers.”
  • Invalid number format: Prevent crashes by using safe conversion (Double(text) with guards).
  • Division by zero: Return a controlled error message.
  • Very long decimals: Format output using NumberFormatter.
  • Negative values: Ensure operations still work correctly.

Better Number Formatting

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 6
formatter.minimumFractionDigits = 0
formatter.numberStyle = .decimal

let output = formatter.string(from: NSNumber(value: result)) ?? "\(result)"

5) Testing Your Swift Calculator

Testing is where your calculator becomes reliable software instead of a demo. Write unit tests for each operation and every error case:

  • Addition with integers and decimals
  • Subtraction yielding negative numbers
  • Multiplication by zero
  • Division success and division-by-zero failure
  • Large and small decimal values

With tests in place, you can refactor confidently and add features like memory keys or scientific operations without breaking basics.

6) Next Features to Add

Once your basic calculator is stable, here are practical upgrades:

  • History list of previous calculations
  • Copy result to clipboard
  • Dark mode support
  • Scientific functions: sin, cos, tan, log, square root
  • Haptic feedback on button tap

Final Thoughts

A calculator in Swift is a fantastic project because it combines UI design, input parsing, state management, and algorithmic thinking in one compact app. Build the logic first, keep your architecture clean, validate all inputs, and test thoroughly. If you do that, you will have both a useful app and a strong foundation for larger iOS projects.

🔗 Related Calculators

🔗 Related Calculators