Practical examples of simple calculator app examples in Swift

If you’re learning iOS development, building a calculator is one of the friendliest ways to get your hands dirty with Swift. In this guide, we’ll walk through several practical examples of simple calculator app examples in Swift, ranging from a bare‑bones command‑line tool to a more polished UIKit or SwiftUI interface. Instead of just dumping code, we’ll talk through how and why each example works, so you can adapt the patterns to your own apps. You’ll see an example of a basic four‑function calculator, a tip calculator, a unit converter, and more. These real examples will help you practice layout, state management, and user input handling in a way that actually feels useful, not academic. By the end, you’ll have multiple Swift code snippets you can copy, tweak, and expand, along with a clearer mental model of how simple calculator logic fits into modern iOS development in 2024 and beyond.
Written by
Taylor
Published
Updated

Starter example of a simple calculator app in Swift (command line)

Let’s kick off with one of the simplest examples of simple calculator app examples in Swift: a tiny command‑line calculator. No UI frameworks, just Swift logic. This helps you focus on the math and control flow before worrying about buttons and layouts.

import Foundation

func calculate(_ a: Double, _ b: Double, op: String) -> Double? {
    switch op {
    case "+": return a + b
    case "-": return a - b
    case "*": return a * b
    case "/": return b != 0 ? a / b : nil
    default: return nil
    }
}

print("Enter first number:", terminator: " ")
let a = Double(readLine() ?? "") ?? 0

print("Enter operator (+, -, *, /):", terminator: " ")
let op = readLine() ?? "+"

print("Enter second number:", terminator: " ")
let b = Double(readLine() ?? "") ?? 0

if let result = calculate(a, b, op: op) {
    print("Result: \(result)")
} else {
    print("Error: invalid operation")
}

This first example of a calculator app keeps everything in one file. You read user input, pass it to a calculate function, then print the result. It’s not pretty, but it mirrors the same logic you’ll reuse when you move into a full iOS app.


UIKit example of a simple four‑function calculator

Now let’s move into iOS land. One of the best examples of simple calculator app examples in Swift is a classic four‑function calculator built with UIKit. Think of the default iOS Calculator app, but stripped to the basics.

You’ll need:

  • A label to show the current value
  • Digit buttons (0–9)
  • Operator buttons (+, −, ×, ÷, =)
  • A clear button (C)

Here’s a simplified ViewController that you can wire up to a storyboard with @IBAction connections.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var displayLabel: UILabel!

    private var currentValue: Double = 0
    private var previousValue: Double = 0
    private var currentOperator: String?
    private var isTypingNumber = false

    @IBAction func digitTapped(_ sender: UIButton) {
        guard let digitText = sender.currentTitle else { return }

        if isTypingNumber {
            displayLabel.text = (displayLabel.text ?? "0") + digitText
        } else {
            displayLabel.text = digitText
            isTypingNumber = true
        }
    }

    @IBAction func operatorTapped(_ sender: UIButton) {
        guard let op = sender.currentTitle,
              let text = displayLabel.text,
              let value = Double(text) else { return }

        if currentOperator != nil {
            // Perform pending operation first
            previousValue = performOperation(lhs: previousValue, rhs: value, op: currentOperator)
        } else {
            previousValue = value
        }

        currentOperator = op == "=" ? nil : op
        isTypingNumber = false
        displayLabel.text = String(previousValue)
    }

    @IBAction func clearTapped(_ sender: UIButton) {
        currentValue = 0
        previousValue = 0
        currentOperator = nil
        isTypingNumber = false
        displayLabel.text = "0"
    }

    private func performOperation(lhs: Double, rhs: Double, op: String?) -> Double {
        switch op {
        case "+": return lhs + rhs
        case "−": return lhs - rhs
        case "×": return lhs * rhs
        case "÷": return rhs == 0 ? lhs : lhs / rhs
        default: return rhs
        }
    }
}

This UIKit example of a simple calculator app shows you how to:

  • Keep track of state (previousValue, currentOperator)
  • Update the display label as the user taps digits
  • Chain operations (2 + 3 + 4 = 9)

You can extend this with a decimal point button, a +/- toggle, and percentage handling, just like the built‑in iOS app.


SwiftUI example of a simple calculator app in 2024

If you’re starting fresh in 2024, SwiftUI is where most tutorials and new projects are heading. Among the best examples of simple calculator app examples in Swift, a SwiftUI version really shows how modern state management works.

Here’s a minimal SwiftUI calculator that supports basic operations:

import SwiftUI

enum CalcOperation {
    case add, subtract, multiply, divide, none
}

struct ContentView: View {
    @State private var display: String = "0"
    @State private var previousValue: Double = 0
    @State private var currentOperation: CalcOperation = .none
    @State private var isTypingNumber = false

    var body: some View {
        VStack(spacing: 16) {
            Spacer()

            Text(display)
                .font(.system(size: 64, weight: .light, design: .rounded))
                .frame(maxWidth: .infinity, alignment: .trailing)
                .padding()

            VStack(spacing: 12) {
                HStack(spacing: 12) {
                    calcButton("7"); calcButton("8"); calcButton("9"); opButton("÷", .divide)
                }
                HStack(spacing: 12) {
                    calcButton("4"); calcButton("5"); calcButton("6"); opButton("×", .multiply)
                }
                HStack(spacing: 12) {
                    calcButton("1"); calcButton("2"); calcButton("3"); opButton("−", .subtract)
                }
                HStack(spacing: 12) {
                    calcButton("0"); calcButton("."); equalsButton(); opButton("+", .add)
                }
            }
            .padding(.bottom)
        }
        .padding()
    }

    private func calcButton(_ title: String) -> some View {
        Button(title) {
            handleDigit(title)
        }
        .font(.title)
        .frame(maxWidth: .infinity, maxHeight: 60)
        .background(Color.gray.opacity(0.2))
        .cornerRadius(12)
    }

    private func opButton(_ symbol: String, _ op: CalcOperation) -> some View {
        Button(symbol) {
            handleOperator(op)
        }
        .font(.title)
        .frame(maxWidth: .infinity, maxHeight: 60)
        .background(Color.orange)
        .foregroundColor(.white)
        .cornerRadius(12)
    }

    private func equalsButton() -> some View {
        Button("=") {
            handleEquals()
        }
        .font(.title)
        .frame(maxWidth: .infinity, maxHeight: 60)
        .background(Color.blue)
        .foregroundColor(.white)
        .cornerRadius(12)
    }

    private func handleDigit(_ digit: String) {
        if isTypingNumber {
            if digit == "." && display.contains(".") { return }
            display += digit
        } else {
            display = digit == "." ? "0." : digit
            isTypingNumber = true
        }
    }

    private func handleOperator(_ op: CalcOperation) {
        if let value = Double(display) {
            if currentOperation == .none {
                previousValue = value
            } else {
                previousValue = performOperation(lhs: previousValue, rhs: value, op: currentOperation)
            }
        }
        isTypingNumber = false
        currentOperation = op
        display = String(previousValue)
    }

    private func handleEquals() {
        if let value = Double(display) {
            let result = performOperation(lhs: previousValue, rhs: value, op: currentOperation)
            display = String(result)
            previousValue = result
            currentOperation = .none
            isTypingNumber = false
        }
    }

    private func performOperation(lhs: Double, rhs: Double, op: CalcOperation) -> Double {
        switch op {
        case .add: return lhs + rhs
        case .subtract: return lhs - rhs
        case .multiply: return lhs * rhs
        case .divide: return rhs == 0 ? lhs : lhs / rhs
        case .none: return rhs
        }
    }
}

This SwiftUI example shows how a simple calculator app can be built using state variables and small helper views. Among real examples of modern Swift code, this pattern—@State for UI data, small helper functions for behavior—is something you’ll see repeatedly in 2024 tutorials and production apps.


Real examples include a tip calculator in Swift

Not every calculator has to look like a math textbook. One very practical example of a simple calculator app in Swift is a tip calculator. It’s still just arithmetic, but now it feels like something you might actually ship.

Here’s a SwiftUI version:

import SwiftUI

struct TipCalculatorView: View {
    @State private var billAmount: String = ""
    @State private var tipPercentage: Double = 15

    private var billValue: Double { Double(billAmount) ?? 0 }
    private var tipValue: Double { billValue * tipPercentage / 100 }
    private var totalValue: Double { billValue + tipValue }

    var body: some View {
        Form {
            Section(header: Text("Bill")) {
                TextField("Amount", text: $billAmount)
                    .keyboardType(.decimalPad)
            }

            Section(header: Text("Tip")) {
                Slider(value: $tipPercentage, in: 0...30, step: 1) {
                    Text("Tip Percentage")
                }
                Text("Tip: $\(tipValue, specifier: "%.2f")")
                Text("Total: $\(totalValue, specifier: "%.2f")")
            }
        }
        .navigationTitle("Tip Calculator")
    }
}

This is one of the best examples of how a “calculator” can be domain‑specific. You’re still calculating, but with a focus on a real‑world task. These kinds of examples of simple calculator app examples in Swift are perfect for portfolios because they show both math logic and user‑friendly design.


Examples of simple calculator app examples in Swift for unit conversion

Another family of real examples includes unit converters: temperature, distance, weight, and so on. These are basically calculators with a different coat of paint.

Here’s a temperature converter between Fahrenheit and Celsius using SwiftUI:

import SwiftUI

struct TemperatureConverterView: View {
    @State private var input: String = ""
    @State private var isFahrenheitToCelsius = true

    private var inputValue: Double { Double(input) ?? 0 }

    private var outputValue: Double {
        if isFahrenheitToCelsius {
            // (F − 32) × 5/9
            return (inputValue - 32) * 5 / 9
        } else {
            // (C × 9/5) + 32
            return (inputValue * 9 / 5) + 32
        }
    }

    var body: some View {
        Form {
            Section(header: Text("Input")) {
                TextField("Temperature", text: $input)
                    .keyboardType(.decimalPad)
                Picker("Direction", selection: $isFahrenheitToCelsius) {
                    Text("F → C").tag(true)
                    Text("C → F").tag(false)
                }
                .pickerStyle(.segmented)
            }

            Section(header: Text("Output")) {
                Text("Result: \(outputValue, specifier: "%.1f")")
            }
        }
        .navigationTitle("Temp Converter")
    }
}

As a bonus, this gives you a chance to think about units and conversions—topics that also matter in health and science apps. For example, organizations like the National Institute of Standards and Technology offer reliable references for unit definitions and conversions.


Examples include a BMI calculator using Swift

A slightly more advanced example of a simple calculator app in Swift is a BMI (Body Mass Index) calculator. It’s still just a formula, but you’re now dealing with categories and user feedback.

The BMI formula is:

BMI = weight(kg) / (height(m))²

If you prefer pounds and inches, you can multiply by a factor of 703. Health agencies like the Centers for Disease Control and Prevention (CDC) explain BMI and its categories.

Here’s a SwiftUI BMI calculator that uses pounds and inches:

import SwiftUI

struct BMICalculatorView: View {
    @State private var weight: String = ""   // in pounds
    @State private var height: String = ""   // in inches

    private var bmi: Double {
        let w = Double(weight) ?? 0
        let h = Double(height) ?? 0
        guard w > 0, h > 0 else { return 0 }
        return (w / (h * h)) * 703
    }

    private var category: String {
        switch bmi {
        case 0..<18.5: return "Underweight"
        case 18.5..<25: return "Normal weight"
        case 25..<30: return "Overweight"
        case 30...: return "Obesity"
        default: return ""
        }
    }

    var body: some View {
        Form {
            Section(header: Text("Your Info")) {
                TextField("Weight (lb)", text: $weight)
                    .keyboardType(.decimalPad)
                TextField("Height (in)", text: $height)
                    .keyboardType(.decimalPad)
            }

            Section(header: Text("Result")) {
                Text("BMI: \(bmi, specifier: "%.1f")")
                if !category.isEmpty {
                    Text("Category: \(category)")
                }
            }
        }
        .navigationTitle("BMI Calculator")
    }
}

This is one of the more realistic examples of simple calculator app examples in Swift, because it mirrors features you’ll see in health apps from organizations like Mayo Clinic and NIH.


Currency converter example of a simple calculator app

Another popular category of examples includes currency converters. For learning purposes, you can hard‑code a rate instead of calling a live API.

import SwiftUI

struct CurrencyConverterView: View {
    @State private var usd: String = ""
    private let rateToEuro: Double = 0.93   // example static rate

    private var euro: Double {
        let usdValue = Double(usd) ?? 0
        return usdValue * rateToEuro
    }

    var body: some View {
        Form {
            Section(header: Text("USD")) {
                TextField("Amount in USD", text: $usd)
                    .keyboardType(.decimalPad)
            }

            Section(header: Text("EUR")) {
                Text("€ \(euro, specifier: "%.2f")")
            }
        }
        .navigationTitle("Currency Converter")
    }
}

This example of a simple calculator app in Swift is great for practicing:

  • Formatting numbers
  • Handling user input
  • Thinking about where to plug in real‑time data later

In a production app, you might pull exchange rates from a trusted financial API, but for now the calculator logic is the star.


Chaining all these examples of simple calculator app examples in Swift

By now, we’ve walked through several examples of simple calculator app examples in Swift:

  • A command‑line calculator
  • A UIKit four‑function calculator
  • A SwiftUI basic calculator
  • A tip calculator
  • A temperature converter
  • A BMI calculator
  • A currency converter

Each one follows the same basic pattern:

  • Take input (text fields, buttons, sliders)
  • Convert input to numbers
  • Apply a formula or operation
  • Show the result in a friendly way

Once you notice that pattern, you can invent your own calculators easily. Maybe you build a mortgage payment calculator, or a simple loan interest calculator. These are just more real examples of the same idea.

A practical way to grow is to start with the plain four‑function calculator example of a Swift app, then:

  • Add a new screen (SwiftUI NavigationStack or UIKit UINavigationController)
  • Drop in one of the specialized calculators (tip, BMI, temperature)
  • Share common formatting helpers across them

Suddenly you don’t just have isolated code snippets—you have a small “calculator suite” app that shows off multiple examples of simple calculator app examples in Swift in one place.


FAQ about Swift calculator examples

Q: What are some good examples of simple calculator app examples in Swift for beginners?
Solid starter ideas include a basic four‑function calculator, a tip calculator, a temperature converter, a BMI calculator, and a currency converter. Each one is small enough to finish in a weekend but rich enough to teach you state, input handling, and layout.

Q: Which is better for a calculator app in 2024, UIKit or SwiftUI?
If you’re starting now, SwiftUI is usually the better bet. It’s the direction Apple is pushing, and it makes layout for calculator‑style screens very approachable. UIKit is still important for legacy projects, so trying at least one UIKit example of a calculator app is worth your time.

Q: How can I avoid messy logic when adding more operations?
Keep your math in small functions or separate types. For instance, a CalculatorEngine struct with a performOperation method makes it easier to test and reuse. Then your SwiftUI or UIKit view just calls that engine instead of stuffing all the logic into button handlers.

Q: Are there real examples of production apps that started as simple calculators?
Many finance, fitness, and health apps began life as small calculators: calorie trackers, savings estimators, BMI tools, and so on. Over time, they added persistence, charts, and APIs. Looking at resources from organizations like Harvard University can give you more ideas for turning simple class projects into more polished apps.

Q: How should I test my Swift calculator apps?
Write unit tests for your core calculation functions (addition, conversion formulas, BMI, etc.). Swift’s XCTest makes it straightforward to feed in known inputs and verify outputs. This matters even for small calculator apps, because it builds habits that carry over to larger projects.

Explore More Swift Code Snippets

Discover more examples and insights in this category.

View All Swift Code Snippets