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
  • Blog
  • 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
GeometryCalculatorViewController.swiftEquationSolverViewController.swift
GeometryCalculatorViewController.swift
Raw Download
Find: Go to:
//
//  GeometryCalculatorViewController.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 GeometryCalculatorViewController: UIViewController {
    
    // MARK: - Outlets
    @IBOutlet weak var shapeSegmentedControl: UISegmentedControl!
    @IBOutlet weak var dimensionSegmentedControl: UISegmentedControl!
    @IBOutlet weak var inputContainerView: UIView!
    @IBOutlet weak var resultTextView: UITextView!
    @IBOutlet weak var calculateButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    
    // 2D Shape Outlets
    @IBOutlet weak var length2DTextField: UITextField!
    @IBOutlet weak var width2DTextField: UITextField!
    @IBOutlet weak var radius2DTextField: UITextField!
    @IBOutlet weak var height2DTextField: UITextField!
    @IBOutlet weak var base2DTextField: UITextField!
    
    // 3D Shape Outlets
    @IBOutlet weak var length3DTextField: UITextField!
    @IBOutlet weak var width3DTextField: UITextField!
    @IBOutlet weak var height3DTextField: UITextField!
    @IBOutlet weak var radius3DTextField: UITextField!
    @IBOutlet weak var depth3DTextField: UITextField!
    
    // MARK: - Properties
    private var currentShape: GeometryShape = .rectangle
    private var currentDimension: GeometryDimension = .twoD
    private let geometryCalculator = GeometryCalculatorService()
    
    enum GeometryShape: String, CaseIterable {
        case rectangle = "Rectangle"
        case circle = "Circle"
        case triangle = "Triangle"
        case square = "Square"
        case ellipse = "Ellipse"
        case trapezoid = "Trapezoid"
        case cube = "Cube"
        case sphere = "Sphere"
        case cylinder = "Cylinder"
        case cone = "Cone"
        case pyramid = "Pyramid"
        case prism = "Prism"
        
        var icon: String {
            switch self {
            case .rectangle: return "rectangle"
            case .circle: return "circle"
            case .triangle: return "triangle"
            case .square: return "square"
            case .ellipse: return "oval"
            case .trapezoid: return "trapezoid"
            case .cube: return "cube"
            case .sphere: return "circle.fill"
            case .cylinder: return "cylinder"
            case .cone: return "cone"
            case .pyramid: return "pyramid"
            case .prism: return "prism"
            }
        }
        
        var is2D: Bool {
            switch self {
            case .rectangle, .circle, .triangle, .square, .ellipse, .trapezoid:
                return true
            default:
                return false
            }
        }
        
        var is3D: Bool {
            return !is2D
        }
    }
    
    enum GeometryDimension: String, CaseIterable {
        case twoD = "2D Shapes"
        case threeD = "3D Shapes"
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupSegmentedControls()
        setupInputViews()
        showRectangleInputs()
    }
    
    // MARK: - Setup
    private func setupUI() {
        title = "Geometry Calculator"
        view.backgroundColor = CalculatorTheme.shared.backgroundColor
        
        // Setup result text view
        resultTextView.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        resultTextView.textColor = CalculatorTheme.shared.textColor
        resultTextView.layer.cornerRadius = 12
        resultTextView.layer.borderWidth = 2
        resultTextView.layer.borderColor = CalculatorTheme.shared.accentColor.cgColor
        resultTextView.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        resultTextView.isEditable = false
        
        // Setup buttons
        setupButton(calculateButton, title: "Calculate", color: .systemGreen)
        setupButton(clearButton, title: "Clear", color: .systemRed)
    }
    
    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 setupSegmentedControls() {
        // Setup dimension segmented control
        dimensionSegmentedControl.removeAllSegments()
        for (index, dimension) in GeometryDimension.allCases.enumerated() {
            dimensionSegmentedControl.insertSegment(withTitle: dimension.rawValue, at: index, animated: false)
        }
        dimensionSegmentedControl.selectedSegmentIndex = 0
        dimensionSegmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        dimensionSegmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        dimensionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        dimensionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
        
        // Setup shape segmented control
        updateShapeSegmentedControl()
    }
    
    private func updateShapeSegmentedControl() {
        shapeSegmentedControl.removeAllSegments()
        
        let shapes = currentDimension == .twoD ? 
            GeometryShape.allCases.filter { $0.is2D } : 
            GeometryShape.allCases.filter { $0.is3D }
        
        for (index, shape) in shapes.enumerated() {
            shapeSegmentedControl.insertSegment(withTitle: shape.rawValue, at: index, animated: false)
        }
        
        shapeSegmentedControl.selectedSegmentIndex = 0
        shapeSegmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        shapeSegmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        shapeSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        shapeSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
        
        // Update current shape
        if let firstShape = shapes.first {
            currentShape = firstShape
        }
    }
    
    private func setupInputViews() {
        // Setup all text fields with consistent styling
        let textFields = [
            length2DTextField, width2DTextField, radius2DTextField, height2DTextField, base2DTextField,
            length3DTextField, width3DTextField, height3DTextField, radius3DTextField, depth3DTextField
        ].compactMap { $0 }
        
        for textField in textFields {
            textField.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
            textField.textColor = CalculatorTheme.shared.textColor
            textField.layer.cornerRadius = 8
            textField.layer.borderWidth = 1
            textField.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
            textField.textAlignment = .center
            textField.font = UIFont.systemFont(ofSize: 16)
            textField.keyboardType = .decimalPad
        }
    }
    
    // MARK: - Actions
    @IBAction func dimensionChanged(_ sender: UISegmentedControl) {
        currentDimension = GeometryDimension.allCases[sender.selectedSegmentIndex]
        updateShapeSegmentedControl()
        switchToShape(currentShape)
    }
    
    @IBAction func shapeChanged(_ sender: UISegmentedControl) {
        let shapes = currentDimension == .twoD ? 
            GeometryShape.allCases.filter { $0.is2D } : 
            GeometryShape.allCases.filter { $0.is3D }
        
        if sender.selectedSegmentIndex < shapes.count {
            currentShape = shapes[sender.selectedSegmentIndex]
            switchToShape(currentShape)
        }
    }
    
    @IBAction func calculateButtonPressed(_ sender: UIButton) {
        performCalculation()
    }
    
    @IBAction func clearButtonPressed(_ sender: UIButton) {
        clearAllInputs()
    }
    
    // MARK: - Methods
    private func switchToShape(_ shape: GeometryShape) {
        hideAllInputViews()
        
        switch shape {
        case .rectangle:
            showRectangleInputs()
        case .circle:
            showCircleInputs()
        case .triangle:
            showTriangleInputs()
        case .square:
            showSquareInputs()
        case .ellipse:
            showEllipseInputs()
        case .trapezoid:
            showTrapezoidInputs()
        case .cube:
            showCubeInputs()
        case .sphere:
            showSphereInputs()
        case .cylinder:
            showCylinderInputs()
        case .cone:
            showConeInputs()
        case .pyramid:
            showPyramidInputs()
        case .prism:
            showPrismInputs()
        }
        
        clearResult()
    }
    
    private func hideAllInputViews() {
        inputContainerView.subviews.forEach { $0.isHidden = true }
    }
    
    private func showRectangleInputs() {
        length2DTextField.isHidden = false
        width2DTextField.isHidden = false
        
        length2DTextField.placeholder = "Length"
        width2DTextField.placeholder = "Width"
    }
    
    private func showCircleInputs() {
        radius2DTextField.isHidden = false
        radius2DTextField.placeholder = "Radius"
    }
    
    private func showTriangleInputs() {
        base2DTextField.isHidden = false
        height2DTextField.isHidden = false
        
        base2DTextField.placeholder = "Base"
        height2DTextField.placeholder = "Height"
    }
    
    private func showSquareInputs() {
        length2DTextField.isHidden = false
        length2DTextField.placeholder = "Side Length"
    }
    
    private func showEllipseInputs() {
        radius2DTextField.isHidden = false
        height2DTextField.isHidden = false
        
        radius2DTextField.placeholder = "Semi-Major Axis"
        height2DTextField.placeholder = "Semi-Minor Axis"
    }
    
    private func showTrapezoidInputs() {
        base2DTextField.isHidden = false
        height2DTextField.isHidden = false
        length2DTextField.isHidden = false
        
        base2DTextField.placeholder = "Base 1"
        length2DTextField.placeholder = "Base 2"
        height2DTextField.placeholder = "Height"
    }
    
    private func showCubeInputs() {
        length3DTextField.isHidden = false
        length3DTextField.placeholder = "Edge Length"
    }
    
    private func showSphereInputs() {
        radius3DTextField.isHidden = false
        radius3DTextField.placeholder = "Radius"
    }
    
    private func showCylinderInputs() {
        radius3DTextField.isHidden = false
        height3DTextField.isHidden = false
        
        radius3DTextField.placeholder = "Radius"
        height3DTextField.placeholder = "Height"
    }
    
    private func showConeInputs() {
        radius3DTextField.isHidden = false
        height3DTextField.isHidden = false
        
        radius3DTextField.placeholder = "Radius"
        height3DTextField.placeholder = "Height"
    }
    
    private func showPyramidInputs() {
        length3DTextField.isHidden = false
        width3DTextField.isHidden = false
        height3DTextField.isHidden = false
        
        length3DTextField.placeholder = "Base Length"
        width3DTextField.placeholder = "Base Width"
        height3DTextField.placeholder = "Height"
    }
    
    private func showPrismInputs() {
        length3DTextField.isHidden = false
        width3DTextField.isHidden = false
        height3DTextField.isHidden = false
        depth3DTextField.isHidden = false
        
        length3DTextField.placeholder = "Length"
        width3DTextField.placeholder = "Width"
        height3DTextField.placeholder = "Height"
        depth3DTextField.placeholder = "Depth"
    }
    
    private func performCalculation() {
        view.endEditing(true)
        
        switch currentShape {
        case .rectangle:
            calculateRectangle()
        case .circle:
            calculateCircle()
        case .triangle:
            calculateTriangle()
        case .square:
            calculateSquare()
        case .ellipse:
            calculateEllipse()
        case .trapezoid:
            calculateTrapezoid()
        case .cube:
            calculateCube()
        case .sphere:
            calculateSphere()
        case .cylinder:
            calculateCylinder()
        case .cone:
            calculateCone()
        case .pyramid:
            calculatePyramid()
        case .prism:
            calculatePrism()
        }
    }
    
    private func calculateRectangle() {
        guard let length = Double(length2DTextField.text ?? ""),
              let width = Double(width2DTextField.text ?? "") else {
            showError("Please enter valid length and width")
            return
        }
        
        let result = geometryCalculator.calculateRectangle(length: length, width: width)
        displayResult(result)
    }
    
    private func calculateCircle() {
        guard let radius = Double(radius2DTextField.text ?? "") else {
            showError("Please enter valid radius")
            return
        }
        
        let result = geometryCalculator.calculateCircle(radius: radius)
        displayResult(result)
    }
    
    private func calculateTriangle() {
        guard let base = Double(base2DTextField.text ?? ""),
              let height = Double(height2DTextField.text ?? "") else {
            showError("Please enter valid base and height")
            return
        }
        
        let result = geometryCalculator.calculateTriangle(base: base, height: height)
        displayResult(result)
    }
    
    private func calculateSquare() {
        guard let side = Double(length2DTextField.text ?? "") else {
            showError("Please enter valid side length")
            return
        }
        
        let result = geometryCalculator.calculateSquare(side: side)
        displayResult(result)
    }
    
    private func calculateEllipse() {
        guard let semiMajor = Double(radius2DTextField.text ?? ""),
              let semiMinor = Double(height2DTextField.text ?? "") else {
            showError("Please enter valid semi-major and semi-minor axes")
            return
        }
        
        let result = geometryCalculator.calculateEllipse(semiMajor: semiMajor, semiMinor: semiMinor)
        displayResult(result)
    }
    
    private func calculateTrapezoid() {
        guard let base1 = Double(base2DTextField.text ?? ""),
              let base2 = Double(length2DTextField.text ?? ""),
              let height = Double(height2DTextField.text ?? "") else {
            showError("Please enter valid base lengths and height")
            return
        }
        
        let result = geometryCalculator.calculateTrapezoid(base1: base1, base2: base2, height: height)
        displayResult(result)
    }
    
    private func calculateCube() {
        guard let edge = Double(length3DTextField.text ?? "") else {
            showError("Please enter valid edge length")
            return
        }
        
        let result = geometryCalculator.calculateCube(edge: edge)
        displayResult(result)
    }
    
    private func calculateSphere() {
        guard let radius = Double(radius3DTextField.text ?? "") else {
            showError("Please enter valid radius")
            return
        }
        
        let result = geometryCalculator.calculateSphere(radius: radius)
        displayResult(result)
    }
    
    private func calculateCylinder() {
        guard let radius = Double(radius3DTextField.text ?? ""),
              let height = Double(height3DTextField.text ?? "") else {
            showError("Please enter valid radius and height")
            return
        }
        
        let result = geometryCalculator.calculateCylinder(radius: radius, height: height)
        displayResult(result)
    }
    
    private func calculateCone() {
        guard let radius = Double(radius3DTextField.text ?? ""),
              let height = Double(height3DTextField.text ?? "") else {
            showError("Please enter valid radius and height")
            return
        }
        
        let result = geometryCalculator.calculateCone(radius: radius, height: height)
        displayResult(result)
    }
    
    private func calculatePyramid() {
        guard let length = Double(length3DTextField.text ?? ""),
              let width = Double(width3DTextField.text ?? ""),
              let height = Double(height3DTextField.text ?? "") else {
            showError("Please enter valid base dimensions and height")
            return
        }
        
        let result = geometryCalculator.calculatePyramid(length: length, width: width, height: height)
        displayResult(result)
    }
    
    private func calculatePrism() {
        guard let length = Double(length3DTextField.text ?? ""),
              let width = Double(width3DTextField.text ?? ""),
              let height = Double(height3DTextField.text ?? ""),
              let depth = Double(depth3DTextField.text ?? "") else {
            showError("Please enter valid dimensions")
            return
        }
        
        let result = geometryCalculator.calculatePrism(length: length, width: width, height: height, depth: depth)
        displayResult(result)
    }
    
    private func displayResult(_ result: GeometryCalculationResult) {
        let resultText = formatResult(result)
        resultTextView.text = resultText
        
        // Animate result appearance
        resultTextView.alpha = 0
        UIView.animate(withDuration: 0.5) {
            self.resultTextView.alpha = 1
        }
        
        // Save to history
        saveToHistory(result: resultText)
    }
    
    private func formatResult(_ result: GeometryCalculationResult) -> String {
        var formattedResult = ""
        
        switch result {
        case .rectangle(let area, let perimeter):
            formattedResult = """
            📐 Rectangle Results
            
            Area: \(String(format: "%.2f", area)) square units
            Perimeter: \(String(format: "%.2f", perimeter)) units
            
            Formulas:
            • Area = length × width
            • Perimeter = 2 × (length + width)
            """
            
        case .circle(let area, let circumference):
            formattedResult = """
            ⭕ Circle Results
            
            Area: \(String(format: "%.2f", area)) square units
            Circumference: \(String(format: "%.2f", circumference)) units
            
            Formulas:
            • Area = π × r²
            • Circumference = 2 × π × r
            """
            
        case .triangle(let area, let perimeter):
            formattedResult = """
            🔺 Triangle Results
            
            Area: \(String(format: "%.2f", area)) square units
            Perimeter: \(String(format: "%.2f", perimeter)) units
            
            Formulas:
            • Area = ½ × base × height
            • Perimeter = sum of all sides
            """
            
        case .square(let area, let perimeter):
            formattedResult = """
            ⬜ Square Results
            
            Area: \(String(format: "%.2f", area)) square units
            Perimeter: \(String(format: "%.2f", perimeter)) units
            
            Formulas:
            • Area = side²
            • Perimeter = 4 × side
            """
            
        case .ellipse(let area, let perimeter):
            formattedResult = """
            🥚 Ellipse Results
            
            Area: \(String(format: "%.2f", area)) square units
            Perimeter: \(String(format: "%.2f", perimeter)) units
            
            Formulas:
            • Area = π × a × b
            • Perimeter ≈ π × [3(a + b) - √((3a + b)(a + 3b))]
            """
            
        case .trapezoid(let area, let perimeter):
            formattedResult = """
            🔺 Trapezoid Results
            
            Area: \(String(format: "%.2f", area)) square units
            Perimeter: \(String(format: "%.2f", perimeter)) units
            
            Formulas:
            • Area = ½ × (base1 + base2) × height
            • Perimeter = sum of all sides
            """
            
        case .cube(let volume, let surfaceArea, let diagonal):
            formattedResult = """
            🎲 Cube Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            Space Diagonal: \(String(format: "%.2f", diagonal)) units
            
            Formulas:
            • Volume = edge³
            • Surface Area = 6 × edge²
            • Diagonal = edge × √3
            """
            
        case .sphere(let volume, let surfaceArea):
            formattedResult = """
            🌐 Sphere Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            
            Formulas:
            • Volume = (4/3) × π × r³
            • Surface Area = 4 × π × r²
            """
            
        case .cylinder(let volume, let surfaceArea):
            formattedResult = """
            🥫 Cylinder Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            
            Formulas:
            • Volume = π × r² × h
            • Surface Area = 2πr(r + h)
            """
            
        case .cone(let volume, let surfaceArea):
            formattedResult = """
            🎯 Cone Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            
            Formulas:
            • Volume = (1/3) × π × r² × h
            • Surface Area = πr(r + √(r² + h²))
            """
            
        case .pyramid(let volume, let surfaceArea):
            formattedResult = """
            🔺 Pyramid Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            
            Formulas:
            • Volume = (1/3) × base_area × height
            • Surface Area = base_area + lateral_area
            """
            
        case .prism(let volume, let surfaceArea):
            formattedResult = """
            🔷 Prism Results
            
            Volume: \(String(format: "%.2f", volume)) cubic units
            Surface Area: \(String(format: "%.2f", surfaceArea)) square units
            
            Formulas:
            • Volume = base_area × height
            • Surface Area = 2 × base_area + lateral_area
            """
        }
        
        return formattedResult
    }
    
    private func clearAllInputs() {
        let textFields = [
            length2DTextField, width2DTextField, radius2DTextField, height2DTextField, base2DTextField,
            length3DTextField, width3DTextField, height3DTextField, radius3DTextField, depth3DTextField
        ].compactMap { $0 }
        
        for textField in textFields {
            textField.text = ""
        }
        
        clearResult()
    }
    
    private func clearResult() {
        resultTextView.text = "Results will appear here..."
    }
    
    private func saveToHistory(result: String) {
        let historyItem = CalculationHistoryItem(
            expression: "\(currentShape.rawValue) Calculation",
            result: result,
            category: "Geometry Calculator",
            date: Date()
        )
        
        CalculationHistoryManager.shared.addHistoryItem(historyItem)
    }
    
    private func showError(_ message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - Geometry Calculator Service
class GeometryCalculatorService {
    
    func calculateRectangle(length: Double, width: Double) -> GeometryCalculationResult {
        let area = length * width
        let perimeter = 2 * (length + width)
        return .rectangle(area: area, perimeter: perimeter)
    }
    
    func calculateCircle(radius: Double) -> GeometryCalculationResult {
        let area = Double.pi * radius * radius
        let circumference = 2 * Double.pi * radius
        return .circle(area: area, circumference: circumference)
    }
    
    func calculateTriangle(base: Double, height: Double) -> GeometryCalculationResult {
        let area = 0.5 * base * height
        // Assuming isosceles triangle for perimeter calculation
        let side = sqrt(pow(base/2, 2) + pow(height, 2))
        let perimeter = base + 2 * side
        return .triangle(area: area, perimeter: perimeter)
    }
    
    func calculateSquare(side: Double) -> GeometryCalculationResult {
        let area = side * side
        let perimeter = 4 * side
        return .square(area: area, perimeter: perimeter)
    }
    
    func calculateEllipse(semiMajor: Double, semiMinor: Double) -> GeometryCalculationResult {
        let area = Double.pi * semiMajor * semiMinor
        // Approximation for ellipse perimeter
        let h = pow((semiMajor - semiMinor), 2) / pow((semiMajor + semiMinor), 2)
        let perimeter = Double.pi * (semiMajor + semiMinor) * (1 + (3 * h) / (10 + sqrt(4 - 3 * h)))
        return .ellipse(area: area, perimeter: perimeter)
    }
    
    func calculateTrapezoid(base1: Double, base2: Double, height: Double) -> GeometryCalculationResult {
        let area = 0.5 * (base1 + base2) * height
        // Assuming isosceles trapezoid for perimeter calculation
        let side = sqrt(pow(abs(base1 - base2) / 2, 2) + pow(height, 2))
        let perimeter = base1 + base2 + 2 * side
        return .trapezoid(area: area, perimeter: perimeter)
    }
    
    func calculateCube(edge: Double) -> GeometryCalculationResult {
        let volume = edge * edge * edge
        let surfaceArea = 6 * edge * edge
        let diagonal = edge * sqrt(3)
        return .cube(volume: volume, surfaceArea: surfaceArea, diagonal: diagonal)
    }
    
    func calculateSphere(radius: Double) -> GeometryCalculationResult {
        let volume = (4.0 / 3.0) * Double.pi * pow(radius, 3)
        let surfaceArea = 4 * Double.pi * radius * radius
        return .sphere(volume: volume, surfaceArea: surfaceArea)
    }
    
    func calculateCylinder(radius: Double, height: Double) -> GeometryCalculationResult {
        let volume = Double.pi * radius * radius * height
        let surfaceArea = 2 * Double.pi * radius * (radius + height)
        return .cylinder(volume: volume, surfaceArea: surfaceArea)
    }
    
    func calculateCone(radius: Double, height: Double) -> GeometryCalculationResult {
        let volume = (1.0 / 3.0) * Double.pi * radius * radius * height
        let slantHeight = sqrt(radius * radius + height * height)
        let surfaceArea = Double.pi * radius * (radius + slantHeight)
        return .cone(volume: volume, surfaceArea: surfaceArea)
    }
    
    func calculatePyramid(length: Double, width: Double, height: Double) -> GeometryCalculationResult {
        let volume = (1.0 / 3.0) * length * width * height
        let baseArea = length * width
        let slantHeight1 = sqrt(pow(length/2, 2) + pow(height, 2))
        let slantHeight2 = sqrt(pow(width/2, 2) + pow(height, 2))
        let lateralArea = 0.5 * length * slantHeight1 + 0.5 * width * slantHeight2
        let surfaceArea = baseArea + lateralArea
        return .pyramid(volume: volume, surfaceArea: surfaceArea)
    }
    
    func calculatePrism(length: Double, width: Double, height: Double, depth: Double) -> GeometryCalculationResult {
        let volume = length * width * height
        let baseArea = length * width
        let lateralArea = 2 * (length * depth + width * depth)
        let surfaceArea = 2 * baseArea + lateralArea
        return .prism(volume: volume, surfaceArea: surfaceArea)
    }
}

// MARK: - Supporting Types
enum GeometryCalculationResult {
    case rectangle(area: Double, perimeter: Double)
    case circle(area: Double, circumference: Double)
    case triangle(area: Double, perimeter: Double)
    case square(area: Double, perimeter: Double)
    case ellipse(area: Double, perimeter: Double)
    case trapezoid(area: Double, perimeter: Double)
    case cube(volume: Double, surfaceArea: Double, diagonal: Double)
    case sphere(volume: Double, surfaceArea: Double)
    case cylinder(volume: Double, surfaceArea: Double)
    case cone(volume: Double, surfaceArea: Double)
    case pyramid(volume: Double, surfaceArea: Double)
    case prism(volume: Double, surfaceArea: Double)
}
817 lines•29.7 KB
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