help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
swift-ios-calculator
RSK World
swift-ios-calculator
Swift iOS Calculator v1.0 - AI Math Solver + 3D Graphing + Apple Watch Integration + iOS Widgets + Siri Shortcuts + Currency Converter + Scientific Calculator + Matrix Operations + Platform Integration + Modern iOS Development
swift-ios-calculator
  • Assets.xcassets
  • Base.lproj
  • swift-ios-calculator.xcodeproj
  • AIMathSolverViewController.swift26.6 KB
  • AppDelegate.swift1.7 KB
  • CalculatorHistoryViewController.swift6.5 KB
  • CalculatorLogic.swift4.4 KB
  • CalculatorSettingsViewController.swift5.6 KB
  • CalculatorTheme.swift8.3 KB
  • CalculatorUtils.swift6.9 KB
  • CalculatorViewController.swift3.4 KB
  • CalculatorWidget.swift14.3 KB
  • CalculatorWidgetInfo.plist846 B
  • ChemistryCalculatorViewController.swift26.9 KB
  • CurrencyConverterViewController.swift13.3 KB
  • CustomFormulaBuilderViewController.swift22.1 KB
  • EngineeringCalculatorViewController.swift25.7 KB
  • EquationSolverViewController.swift22.8 KB
  • FinancialCalculatorViewController.swift27.5 KB
  • GeometryCalculatorViewController.swift29.7 KB
  • Graphing3DViewController.swift20.8 KB
  • GraphingCalculatorViewController.swift14.7 KB
  • Info.plist3.2 KB
  • LICENSE1.1 KB
  • MainTabBarController.swift22.3 KB
  • MatrixCalculatorViewController.swift26.6 KB
  • PRIVACY_POLICY.md1.6 KB
  • PhysicsCalculatorService.swift8.2 KB
  • ProgrammerCalculatorViewController.swift11 KB
  • README.md8.7 KB
  • RELEASE_NOTES.md6.5 KB
  • SceneDelegate.swift2.8 KB
  • ScientificCalculatorViewController.swift6.2 KB
  • SiriShortcutsManager.swift23.5 KB
  • Swift iOS Calculator.entitlements1.1 KB
  • UnitConverterViewController.swift14 KB
  • WatchCalculatorViewController.swift15.3 KB
  • index.html47.5 KB
EquationSolverViewController.swift
EquationSolverViewController.swift
Raw Download
Find: Go to:
//
//  EquationSolverViewController.swift
//  Swift iOS Calculator
//
//  Created by RSK World on 23/01/2026.
//  Copyright © 2026 RSK World. All rights reserved.
//
//  Developer: Molla Samser (Founder, RSK World)
//  Designer & Tester: Rima Khatun
//  Contact: info@rskworld.com, +91 93305 39277
//  Website: https://rskworld.in
//  Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
//

import UIKit

class EquationSolverViewController: UIViewController {
    
    // MARK: - Outlets
    @IBOutlet weak var equationTextField: UITextField!
    @IBOutlet weak var equationTypeSegmentedControl: UISegmentedControl!
    @IBOutlet weak var solveButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    @IBOutlet weak var solutionTextView: UITextView!
    @IBOutlet weak var stepsTableView: UITableView!
    @IBOutlet weak var graphButton: UIButton!
    @IBOutlet weak var verifyButton: UIButton!
    
    // MARK: - Properties
    private var currentEquation: String = ""
    private var solutionSteps: [SolutionStep] = []
    private var equationType: EquationType = .algebraic
    private var equationSolver = EquationSolverService()
    
    enum EquationType: String, CaseIterable {
        case algebraic = "Algebraic"
        case linear = "Linear"
        case quadratic = "Quadratic"
        case differential = "Differential"
        case system = "System"
        
        var icon: String {
            switch self {
            case .algebraic: return "x.squareroot"
            case .linear: return "line.diagonal"
            case .quadratic: return "x.squareroot.fill"
            case .differential: return "integral"
            case .system: return "rectangle.3.group"
            }
        }
    }
    
    struct SolutionStep {
        let stepNumber: Int
        let description: String
        let equation: String
        let explanation: String
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupTableView()
        setupSegmentedControl()
    }
    
    // MARK: - Setup
    private func setupUI() {
        title = "Equation Solver"
        view.backgroundColor = CalculatorTheme.shared.backgroundColor
        
        // Setup text field
        equationTextField.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        equationTextField.textColor = CalculatorTheme.shared.textColor
        equationTextField.placeholder = "Enter equation (e.g., 2x + 5 = 15)"
        equationTextField.layer.cornerRadius = 12
        equationTextField.layer.borderWidth = 2
        equationTextField.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
        equationTextField.font = UIFont.systemFont(ofSize: 18)
        
        // Setup solution text view
        solutionTextView.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        solutionTextView.textColor = CalculatorTheme.shared.textColor
        solutionTextView.layer.cornerRadius = 12
        solutionTextView.layer.borderWidth = 2
        solutionTextView.layer.borderColor = CalculatorTheme.shared.accentColor.cgColor
        solutionTextView.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        solutionTextView.isEditable = false
        
        // Setup buttons
        setupButton(solveButton, title: "Solve Equation", color: .systemGreen)
        setupButton(clearButton, title: "Clear", color: .systemRed)
        setupButton(graphButton, title: "Graph", color: .systemBlue)
        setupButton(verifyButton, title: "Verify", color: .systemOrange)
    }
    
    private func setupButton(_ button: UIButton, title: String, color: UIColor) {
        button.setTitle(title, for: .normal)
        button.backgroundColor = color
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 8
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
    }
    
    private func setupTableView() {
        stepsTableView.delegate = self
        stepsTableView.dataSource = self
        stepsTableView.backgroundColor = CalculatorTheme.shared.backgroundColor
        stepsTableView.layer.cornerRadius = 12
        stepsTableView.separatorStyle = .none
        
        // Register cell
        stepsTableView.register(UINib(nibName: "SolutionStepCell", bundle: nil), forCellReuseIdentifier: "SolutionStepCell")
    }
    
    private func setupSegmentedControl() {
        equationTypeSegmentedControl.removeAllSegments()
        for (index, type) in EquationType.allCases.enumerated() {
            equationTypeSegmentedControl.insertSegment(withTitle: type.rawValue, at: index, animated: false)
        }
        equationTypeSegmentedControl.selectedSegmentIndex = 0
        equationTypeSegmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        equationTypeSegmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        equationTypeSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        equationTypeSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
    }
    
    // MARK: - Actions
    @IBAction func equationTypeChanged(_ sender: UISegmentedControl) {
        equationType = EquationType.allCases[sender.selectedSegmentIndex]
        updatePlaceholder()
        clearSolution()
    }
    
    @IBAction func solveButtonPressed(_ sender: UIButton) {
        guard let equation = equationTextField.text, !equation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            showAlert(title: "Error", message: "Please enter an equation to solve")
            return
        }
        
        currentEquation = equation
        solveEquation(equation)
    }
    
    @IBAction func clearButtonPressed(_ sender: UIButton) {
        clearAll()
    }
    
    @IBAction func graphButtonPressed(_ sender: UIButton) {
        if !currentEquation.isEmpty {
            graphEquation()
        } else {
            showAlert(title: "Error", message: "Please enter an equation first")
        }
    }
    
    @IBAction func verifyButtonPressed(_ sender: UIButton) {
        if !currentEquation.isEmpty {
            verifySolution()
        } else {
            showAlert(title: "Error", message: "Please enter an equation first")
        }
    }
    
    // MARK: - Methods
    private func solveEquation(_ equation: String) {
        equationSolver.solveEquation(equation, type: equationType) { [weak self] result in
            DispatchQueue.main.async {
                switch result {
                case .success((let solution, let steps)):
                    self?.displaySolution(solution, steps: steps)
                case .failure(let error):
                    self?.showError(error)
                }
            }
        }
    }
    
    private func displaySolution(_ solution: String, steps: [SolutionStep]) {
        solutionTextView.text = solution
        solutionSteps = steps
        stepsTableView.reloadData()
        
        // Animate appearance
        solutionTextView.alpha = 0
        stepsTableView.alpha = 0
        
        UIView.animate(withDuration: 0.5) {
            self.solutionTextView.alpha = 1
            self.stepsTableView.alpha = 1
        }
        
        // Save to history
        saveToHistory(equation: currentEquation, solution: solution)
    }
    
    private func graphEquation() {
        let graphVC = GraphingCalculatorViewController()
        graphVC.setEquation(currentEquation)
        let navController = UINavigationController(rootViewController: graphVC)
        present(navController, animated: true)
    }
    
    private func verifySolution() {
        // Verify the solution by plugging values back into the equation
        equationSolver.verifySolution(currentEquation) { [weak self] result in
            DispatchQueue.main.async {
                switch result {
                case .success(let isCorrect):
                    let message = isCorrect ? "✅ Solution is correct!" : "❌ Solution verification failed"
                    self?.showAlert(title: "Verification", message: message)
                case .failure(let error):
                    self?.showError(error)
                }
            }
        }
    }
    
    private func updatePlaceholder() {
        switch equationType {
        case .algebraic:
            equationTextField.placeholder = "Enter equation (e.g., 2x + 5 = 15)"
        case .linear:
            equationTextField.placeholder = "Enter linear equation (e.g., 3x - 2y = 7)"
        case .quadratic:
            equationTextField.placeholder = "Enter quadratic equation (e.g., x² + 5x + 6 = 0)"
        case .differential:
            equationTextField.placeholder = "Enter differential equation (e.g., dy/dx = 2x)"
        case .system:
            equationTextField.placeholder = "Enter system (e.g., x + y = 10, 2x - y = 5)"
        }
    }
    
    private func clearAll() {
        equationTextField.text = ""
        solutionTextView.text = "Solution will appear here..."
        solutionSteps.removeAll()
        stepsTableView.reloadData()
        currentEquation = ""
    }
    
    private func clearSolution() {
        solutionTextView.text = "Solution will appear here..."
        solutionSteps.removeAll()
        stepsTableView.reloadData()
    }
    
    private func saveToHistory(equation: String, solution: String) {
        let historyItem = CalculationHistoryItem(
            expression: equation,
            result: solution,
            category: "Equation Solver",
            date: Date()
        )
        
        CalculationHistoryManager.shared.addHistoryItem(historyItem)
    }
    
    private func showError(_ error: Error) {
        showAlert(title: "Error", message: "Failed to solve equation: \(error.localizedDescription)")
    }
    
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate
extension EquationSolverViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return solutionSteps.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SolutionStepCell", for: indexPath) as! SolutionStepCell
        let step = solutionSteps[indexPath.row]
        cell.configure(with: step)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
}

// MARK: - Equation Solver Service
class EquationSolverService {
    
    func solveEquation(_ equation: String, type: EquationSolverViewController.EquationType, completion: @escaping (Result<(String, [EquationSolverViewController.SolutionStep]), Error>) -> Void) {
        
        // Simulate solving process
        DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
            do {
                let (solution, steps) = try self.generateSolution(for: equation, type: type)
                DispatchQueue.main.async {
                    completion(.success((solution, steps)))
                }
            } catch {
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
            }
        }
    }
    
    func verifySolution(_ equation: String, completion: @escaping (Result<Bool, Error>) -> Void) {
        // Simulate verification process
        DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
            // Simple verification - in a real app, this would be more sophisticated
            let isCorrect = !equation.contains("invalid")
            DispatchQueue.main.async {
                completion(.success(isCorrect))
            }
        }
    }
    
    private func generateSolution(for equation: String, type: EquationSolverViewController.EquationType) throws -> (String, [EquationSolverViewController.SolutionStep]) {
        
        switch type {
        case .algebraic:
            return generateAlgebraicSolution(equation)
        case .linear:
            return generateLinearSolution(equation)
        case .quadratic:
            return generateQuadraticSolution(equation)
        case .differential:
            return generateDifferentialSolution(equation)
        case .system:
            return generateSystemSolution(equation)
        }
    }
    
    private func generateAlgebraicSolution(_ equation: String) -> (String, [EquationSolverViewController.SolutionStep]) {
        var steps: [EquationSolverViewController.SolutionStep] = []
        
        // Example: 2x + 5 = 15
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 1,
            description: "Start with the given equation",
            equation: equation,
            explanation: "We need to solve for x"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 2,
            description: "Subtract 5 from both sides",
            equation: "2x = 15 - 5",
            explanation: "Isolate the term with x"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 3,
            description: "Simplify",
            equation: "2x = 10",
            explanation: "Combine like terms"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 4,
            description: "Divide both sides by 2",
            equation: "x = 10 ÷ 2",
            explanation: "Solve for x"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 5,
            description: "Final answer",
            equation: "x = 5",
            explanation: "The solution is x = 5"
        ))
        
        let solution = "The equation \(equation) has the solution:\n\nx = 5\n\nVerification:\n2(5) + 5 = 10 + 5 = 15 ✓"
        
        return (solution, steps)
    }
    
    private func generateLinearSolution(_ equation: String) -> (String, [EquationSolverViewController.SolutionStep]) {
        var steps: [EquationSolverViewController.SolutionStep] = []
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 1,
            description: "Identify the linear equation",
            equation: equation,
            explanation: "This is a linear equation in two variables"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 2,
            description: "Solve for one variable",
            equation: "x = (7 + 2y) ÷ 3",
            explanation: "Express x in terms of y"
        ))
        
        let solution = "The linear equation \(equation) represents a line.\n\nGeneral solution: x = (7 + 2y) ÷ 3\n\nThis represents all points (x, y) that satisfy the equation."
        
        return (solution, steps)
    }
    
    private func generateQuadraticSolution(_ equation: String) -> (String, [EquationSolverViewController.SolutionStep]) {
        var steps: [EquationSolverViewController.SolutionStep] = []
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 1,
            description: "Identify the quadratic equation",
            equation: "x² + 5x + 6 = 0",
            explanation: "Standard form: ax² + bx + c = 0"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 2,
            description: "Apply the quadratic formula",
            equation: "x = (-b ± √(b² - 4ac)) / 2a",
            explanation: "Where a = 1, b = 5, c = 6"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 3,
            description: "Calculate the discriminant",
            equation: "Δ = b² - 4ac = 25 - 24 = 1",
            explanation: "The discriminant is positive, so there are two real solutions"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 4,
            description: "Find the solutions",
            equation: "x = (-5 ± √1) / 2",
            explanation: "Calculate both solutions"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 5,
            description: "Final solutions",
            equation: "x₁ = -2, x₂ = -3",
            explanation: "The quadratic equation has two solutions"
        ))
        
        let solution = "The quadratic equation \(equation) has two solutions:\n\nx₁ = -2\nx₂ = -3\n\nThese are the x-intercepts of the parabola."
        
        return (solution, steps)
    }
    
    private func generateDifferentialSolution(_ equation: String) -> (String, [EquationSolverViewController.SolutionStep]) {
        var steps: [EquationSolverViewController.SolutionStep] = []
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 1,
            description: "Identify the differential equation",
            equation: "dy/dx = 2x",
            explanation: "First-order ordinary differential equation"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 2,
            description: "Separate variables",
            equation: "dy = 2x dx",
            explanation: "Move all y terms to one side"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 3,
            description: "Integrate both sides",
            equation: "∫dy = ∫2x dx",
            explanation: "Integrate to find the general solution"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 4,
            description: "Apply integration rules",
            equation: "y = x² + C",
            explanation: "Where C is the constant of integration"
        ))
        
        let solution = "The differential equation \(equation) has the general solution:\n\ny = x² + C\n\nWhere C is an arbitrary constant determined by initial conditions."
        
        return (solution, steps)
    }
    
    private func generateSystemSolution(_ equation: String) -> (String, [EquationSolverViewController.SolutionStep]) {
        var steps: [EquationSolverViewController.SolutionStep] = []
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 1,
            description: "Identify the system of equations",
            equation: "x + y = 10, 2x - y = 5",
            explanation: "System of two linear equations"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 2,
            description: "Add the equations to eliminate y",
            equation: "3x = 15",
            explanation: "Adding eliminates the y variable"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 3,
            description: "Solve for x",
            equation: "x = 5",
            explanation: "Divide both sides by 3"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 4,
            description: "Substitute x back to find y",
            equation: "5 + y = 10",
            explanation: "Use the first equation"
        ))
        
        steps.append(EquationSolverViewController.SolutionStep(
            stepNumber: 5,
            description: "Solve for y",
            equation: "y = 5",
            explanation: "Subtract 5 from both sides"
        ))
        
        let solution = "The system of equations has the unique solution:\n\nx = 5\ny = 5\n\nThis is the intersection point of the two lines."
        
        return (solution, steps)
    }
}

// MARK: - Supporting Classes
class SolutionStepCell: UITableViewCell {
    
    @IBOutlet weak var stepNumberLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var equationLabel: UILabel!
    @IBOutlet weak var explanationLabel: UILabel!
    
    func configure(with step: EquationSolverViewController.SolutionStep) {
        stepNumberLabel.text = "Step \(step.stepNumber)"
        descriptionLabel.text = step.description
        equationLabel.text = step.equation
        explanationLabel.text = step.explanation
        
        // Apply theme
        backgroundColor = CalculatorTheme.shared.backgroundColor
        stepNumberLabel.textColor = CalculatorTheme.shared.accentColor
        descriptionLabel.textColor = CalculatorTheme.shared.textColor
        equationLabel.textColor = CalculatorTheme.shared.textColor
        explanationLabel.textColor = CalculatorTheme.shared.textColor.withAlphaComponent(0.8)
    }
}

struct CalculationHistoryItem {
    let expression: String
    let result: String
    let category: String
    let date: Date
}

class CalculationHistoryManager {
    static let shared = CalculationHistoryManager()
    
    private var historyItems: [CalculationHistoryItem] = []
    
    func addHistoryItem(_ item: CalculationHistoryItem) {
        historyItems.append(item)
        
        // Keep only last 100 items
        if historyItems.count > 100 {
            historyItems.removeFirst(historyItems.count - 100)
        }
        
        // Save to UserDefaults
        saveToUserDefaults()
    }
    
    func getHistoryItems() -> [CalculationHistoryItem] {
        return historyItems
    }
    
    private func saveToUserDefaults() {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(historyItems) {
            UserDefaults.standard.set(encoded, forKey: "CalculationHistory")
        }
    }
    
    private func loadFromUserDefaults() {
        if let data = UserDefaults.standard.data(forKey: "CalculationHistory") {
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([CalculationHistoryItem].self, from: data) {
                historyItems = decoded
            }
        }
    }
}
597 lines•22.8 KB
swift

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer