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.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

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