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
ChemistryCalculatorViewController.swift
ChemistryCalculatorViewController.swift
Raw Download
Find: Go to:
//
//  ChemistryCalculatorViewController.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 ChemistryCalculatorViewController: UIViewController {
    
    // MARK: - Outlets
    @IBOutlet weak var calculatorSegmentedControl: UISegmentedControl!
    @IBOutlet weak var inputContainerView: UIView!
    @IBOutlet weak var resultTextView: UITextView!
    @IBOutlet weak var calculateButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    
    // Molar Mass Outlets
    @IBOutlet weak var chemicalFormulaTextField: UITextField!
    
    // Reaction Outlets
    @IBOutlet weak var reactantsTextField: UITextField!
    @IBOutlet weak var productsTextField: UITextField!
    
    // Concentration Outlets
    @IBOutlet weak var molesTextField: UITextField!
    @IBOutlet weak var volumeTextField: UITextField!
    @IBOutlet weak var massTextField: UITextField!
    @IBOutlet weak var molarMassTextField: UITextField!
    
    // Gas Laws Outlets
    @IBOutlet weak var pressureTextField: UITextField!
    @IBOutlet weak var temperatureTextField: UITextField!
    @IBOutlet weak var gasVolumeTextField: UITextField!
    @IBOutlet weak var gasMolesTextField: UITextField!
    
    // pH Outlets
    @IBOutlet weak var hydrogenIonTextField: UITextField!
    @IBOutlet weak var hydroxideIonTextField: UITextField!
    @IBOutlet weak var acidConcentrationTextField: UITextField!
    
    // MARK: - Properties
    private var currentCalculator: ChemistryCalculatorType = .molarMass
    private let chemistryCalculator = ChemistryCalculatorService()
    
    enum ChemistryCalculatorType: String, CaseIterable {
        case molarMass = "Molar Mass"
        case reaction = "Reaction"
        case concentration = "Concentration"
        case gasLaws = "Gas Laws"
        case pH = "pH Calculator"
        case stoichiometry = "Stoichiometry"
        
        var icon: String {
            switch self {
            case .molarMass: return "atom"
            case .reaction: return "arrow.triangle.2.circlepath"
            case .concentration: return "flask"
            case .gasLaws: return "wind"
            case .pH: return "drop.triangle"
            case .stoichiometry: return "scalemass"
            }
        }
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupSegmentedControl()
        setupInputViews()
        showMolarMassInputs()
    }
    
    // MARK: - Setup
    private func setupUI() {
        title = "Chemistry 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 setupSegmentedControl() {
        calculatorSegmentedControl.removeAllSegments()
        for (index, type) in ChemistryCalculatorType.allCases.enumerated() {
            calculatorSegmentedControl.insertSegment(withTitle: type.rawValue, at: index, animated: false)
        }
        calculatorSegmentedControl.selectedSegmentIndex = 0
        calculatorSegmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        calculatorSegmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        calculatorSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        calculatorSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
    }
    
    private func setupInputViews() {
        // Setup all text fields with consistent styling
        let textFields = [
            chemicalFormulaTextField, reactantsTextField, productsTextField,
            molesTextField, volumeTextField, massTextField, molarMassTextField,
            pressureTextField, temperatureTextField, gasVolumeTextField, gasMolesTextField,
            hydrogenIonTextField, hydroxideIonTextField, acidConcentrationTextField
        ].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
        }
        
        // Set specific keyboard types
        chemicalFormulaTextField.keyboardType = .default
        reactantsTextField.keyboardType = .default
        productsTextField.keyboardType = .default
    }
    
    // MARK: - Actions
    @IBAction func calculatorChanged(_ sender: UISegmentedControl) {
        currentCalculator = ChemistryCalculatorType.allCases[sender.selectedSegmentIndex]
        switchToCalculator(currentCalculator)
    }
    
    @IBAction func calculateButtonPressed(_ sender: UIButton) {
        performCalculation()
    }
    
    @IBAction func clearButtonPressed(_ sender: UIButton) {
        clearAllInputs()
    }
    
    // MARK: - Methods
    private func switchToCalculator(_ type: ChemistryCalculatorType) {
        hideAllInputViews()
        
        switch type {
        case .molarMass:
            showMolarMassInputs()
        case .reaction:
            showReactionInputs()
        case .concentration:
            showConcentrationInputs()
        case .gasLaws:
            showGasLawsInputs()
        case .pH:
            showpHInputs()
        case .stoichiometry:
            showStoichiometryInputs()
        }
        
        clearResult()
    }
    
    private func hideAllInputViews() {
        inputContainerView.subviews.forEach { $0.isHidden = true }
    }
    
    private func showMolarMassInputs() {
        chemicalFormulaTextField.isHidden = false
        chemicalFormulaTextField.placeholder = "Enter chemical formula (e.g., H2O, C6H12O6)"
    }
    
    private func showReactionInputs() {
        reactantsTextField.isHidden = false
        productsTextField.isHidden = false
        
        reactantsTextField.placeholder = "Reactants (e.g., 2H2 + O2)"
        productsTextField.placeholder = "Products (e.g., 2H2O)"
    }
    
    private func showConcentrationInputs() {
        molesTextField.isHidden = false
        volumeTextField.isHidden = false
        massTextField.isHidden = false
        molarMassTextField.isHidden = false
        
        molesTextField.placeholder = "Moles (mol)"
        volumeTextField.placeholder = "Volume (L)"
        massTextField.placeholder = "Mass (g)"
        molarMassTextField.placeholder = "Molar Mass (g/mol)"
    }
    
    private func showGasLawsInputs() {
        pressureTextField.isHidden = false
        temperatureTextField.isHidden = false
        gasVolumeTextField.isHidden = false
        gasMolesTextField.isHidden = false
        
        pressureTextField.placeholder = "Pressure (atm)"
        temperatureTextField.placeholder = "Temperature (K)"
        gasVolumeTextField.placeholder = "Volume (L)"
        gasMolesTextField.placeholder = "Moles (mol)"
    }
    
    private func showpHInputs() {
        hydrogenIonTextField.isHidden = false
        hydroxideIonTextField.isHidden = false
        acidConcentrationTextField.isHidden = false
        
        hydrogenIonTextField.placeholder = "[H+] concentration (M)"
        hydroxideIonTextField.placeholder = "[OH-] concentration (M)"
        acidConcentrationTextField.placeholder = "Acid concentration (M)"
    }
    
    private func showStoichiometryInputs() {
        reactantsTextField.isHidden = false
        productsTextField.isHidden = false
        massTextField.isHidden = false
        
        reactantsTextField.placeholder = "Known reactant (e.g., 2H2)"
        productsTextField.placeholder = "Target product (e.g., H2O)"
        massTextField.placeholder = "Mass of known reactant (g)"
    }
    
    private func performCalculation() {
        view.endEditing(true)
        
        switch currentCalculator {
        case .molarMass:
            calculateMolarMass()
        case .reaction:
            calculateReaction()
        case .concentration:
            calculateConcentration()
        case .gasLaws:
            calculateGasLaws()
        case .pH:
            calculatepH()
        case .stoichiometry:
            calculateStoichiometry()
        }
    }
    
    private func calculateMolarMass() {
        guard let formula = chemicalFormulaTextField.text, !formula.isEmpty else {
            showError("Please enter a chemical formula")
            return
        }
        
        let result = chemistryCalculator.calculateMolarMass(formula: formula)
        displayResult(result)
    }
    
    private func calculateReaction() {
        guard let reactants = reactantsTextField.text, !reactants.isEmpty,
              let products = productsTextField.text, !products.isEmpty else {
            showError("Please enter both reactants and products")
            return
        }
        
        let result = chemistryCalculator.calculateReaction(reactants: reactants, products: products)
        displayResult(result)
    }
    
    private func calculateConcentration() {
        guard let volume = Double(volumeTextField.text ?? "") else {
            showError("Please enter valid volume")
            return
        }
        
        let moles = Double(molesTextField.text ?? "")
        let mass = Double(massTextField.text ?? "")
        let molarMass = Double(molarMassTextField.text ?? "")
        
        let result = chemistryCalculator.calculateConcentration(
            moles: moles,
            volume: volume,
            mass: mass,
            molarMass: molarMass
        )
        displayResult(result)
    }
    
    private func calculateGasLaws() {
        let pressure = Double(pressureTextField.text ?? "")
        let temperature = Double(temperatureTextField.text ?? "")
        let volume = Double(gasVolumeTextField.text ?? "")
        let moles = Double(gasMolesTextField.text ?? "")
        
        let result = chemistryCalculator.calculateGasLaws(
            pressure: pressure,
            temperature: temperature,
            volume: volume,
            moles: moles
        )
        displayResult(result)
    }
    
    private func calculatepH() {
        let hydrogenConcentration = Double(hydrogenIonTextField.text ?? "")
        let hydroxideConcentration = Double(hydroxideIonTextField.text ?? "")
        let acidConcentration = Double(acidConcentrationTextField.text ?? "")
        
        let result = chemistryCalculator.calculatepH(
            hydrogenConcentration: hydrogenConcentration,
            hydroxideConcentration: hydroxideConcentration,
            acidConcentration: acidConcentration
        )
        displayResult(result)
    }
    
    private func calculateStoichiometry() {
        guard let reactants = reactantsTextField.text, !reactants.isEmpty,
              let products = productsTextField.text, !products.isEmpty,
              let mass = Double(massTextField.text ?? "") else {
            showError("Please enter reaction details and mass")
            return
        }
        
        let result = chemistryCalculator.calculateStoichiometry(
            reactants: reactants,
            products: products,
            mass: mass
        )
        displayResult(result)
    }
    
    private func displayResult(_ result: ChemistryCalculationResult) {
        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: ChemistryCalculationResult) -> String {
        var formattedResult = ""
        
        switch result {
        case .molarMass(let formula, let mass, let composition):
            formattedResult = """
            ⚗️ Molar Mass Calculation
            
            Formula: \(formula)
            Molar Mass: \(String(format: "%.2f", mass)) g/mol
            
            Composition:
            \(composition)
            
            Formula: Molar Mass = Σ(atomic mass × number of atoms)
            """
            
        case .reaction(let reactants, let products, let balanced, let type):
            formattedResult = """
            🧪 Chemical Reaction
            
            Reactants: \(reactants)
            Products: \(products)
            
            Balanced Equation:
            \(balanced)
            
            Reaction Type: \(type)
            
            Conservation of mass is maintained in the balanced equation.
            """
            
        case .concentration(let molarity, let molality, let normality):
            formattedResult = """
            🧪 Concentration Calculator
            
            Results:
            • Molarity: \(String(format: "%.2f", molarity)) M
            • Molality: \(String(format: "%.2f", molality)) m
            • Normality: \(String(format: "%.2f", normality)) N
            
            Formulas:
            • Molarity = moles / volume (L)
            • Molality = moles / mass of solvent (kg)
            • Normality = equivalents / volume (L)
            """
            
        case .gasLaws(let pressure, let volume, let temperature, let moles):
            formattedResult = """
            💨 Gas Laws Calculator
            
            Results:
            • Pressure: \(String(format: "%.2f", pressure)) atm
            • Volume: \(String(format: "%.2f", volume)) L
            • Temperature: \(String(format: "%.2f", temperature)) K
            • Moles: \(String(format: "%.2f", moles)) mol
            
            Ideal Gas Law: PV = nRT
            Where R = 0.0821 L·atm/(mol·K)
            """
            
        case .pH(let pH, let pOH, let isAcidic):
            formattedResult = """
            💧 pH Calculator
            
            Results:
            • pH: \(String(format: "%.2f", pH))
            • pOH: \(String(format: "%.2f", pOH))
            • Solution Type: \(isAcidic ? "Acidic" : "Basic")
            
            Formulas:
            • pH = -log[H+]
            • pOH = -log[OH-]
            • pH + pOH = 14
            """
            
        case .stoichiometry(let limitingReactant, let theoreticalYield, let percentYield):
            formattedResult = """
            ⚖️ Stoichiometry Calculator
            
            Results:
            • Limiting Reactant: \(limitingReactant)
            • Theoretical Yield: \(String(format: "%.2f", theoreticalYield)) g
            • Percent Yield: \(String(format: "%.2f", percentYield))%
            
            Stoichiometric calculations based on balanced chemical equation.
            """
        }
        
        return formattedResult
    }
    
    private func clearAllInputs() {
        let textFields = [
            chemicalFormulaTextField, reactantsTextField, productsTextField,
            molesTextField, volumeTextField, massTextField, molarMassTextField,
            pressureTextField, temperatureTextField, gasVolumeTextField, gasMolesTextField,
            hydrogenIonTextField, hydroxideIonTextField, acidConcentrationTextField
        ].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: "\(currentCalculator.rawValue) Calculation",
            result: result,
            category: "Chemistry 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: - Chemistry Calculator Service
class ChemistryCalculatorService {
    
    // Periodic table data (simplified)
    private let atomicMasses: [String: Double] = [
        "H": 1.008, "He": 4.003, "Li": 6.941, "Be": 9.012, "B": 10.81, "C": 12.01,
        "N": 14.01, "O": 16.00, "F": 19.00, "Ne": 20.18, "Na": 22.99, "Mg": 24.31,
        "Al": 26.98, "Si": 28.09, "P": 30.97, "S": 32.07, "Cl": 35.45, "Ar": 39.95,
        "K": 39.10, "Ca": 40.08, "Sc": 44.96, "Ti": 47.87, "V": 50.94, "Cr": 52.00,
        "Mn": 54.94, "Fe": 55.85, "Co": 58.93, "Ni": 58.69, "Cu": 63.55, "Zn": 65.38,
        "Ga": 69.72, "Ge": 72.63, "As": 74.92, "Se": 78.96, "Br": 79.90, "Kr": 83.80,
        "Rb": 85.47, "Sr": 87.62, "Y": 88.91, "Zr": 91.22, "Nb": 92.91, "Mo": 95.94,
        "Tc": 98.00, "Ru": 101.07, "Rh": 102.91, "Pd": 106.42, "Ag": 107.87, "Cd": 112.41,
        "In": 114.82, "Sn": 118.71, "Sb": 121.76, "Te": 127.60, "I": 126.90, "Xe": 131.29
    ]
    
    func calculateMolarMass(formula: String) -> ChemistryCalculationResult {
        let (mass, composition) = parseChemicalFormula(formula)
        return .molarMass(formula: formula, mass: mass, composition: composition)
    }
    
    func calculateReaction(reactants: String, products: String) -> ChemistryCalculationResult {
        let balanced = balanceEquation(reactants: reactants, products: products)
        let type = determineReactionType(reactants: reactants, products: products)
        return .reaction(reactants: reactants, products: products, balanced: balanced, type: type)
    }
    
    func calculateConcentration(moles: Double?, volume: Double, mass: Double?, molarMass: Double?) -> ChemistryCalculationResult {
        var calculatedMoles = moles ?? 0.0
        
        if let mass = mass, let molarMass = molarMass {
            calculatedMoles = mass / molarMass
        }
        
        let molarity = calculatedMoles / volume
        let molality = calculatedMoles / (volume * 0.8) // Assuming density
        let normality = molarity // Assuming monoprotic
        
        return .concentration(molarity: molarity, molality: molality, normality: normality)
    }
    
    func calculateGasLaws(pressure: Double?, temperature: Double?, volume: Double?, moles: Double?) -> ChemistryCalculationResult {
        let R = 0.0821 // L·atm/(mol·K)
        
        var calculatedPressure = pressure ?? 0.0
        var calculatedTemperature = temperature ?? 273.15
        var calculatedVolume = volume ?? 0.0
        var calculatedMoles = moles ?? 0.0
        
        // Calculate missing variable using ideal gas law
        if pressure == nil && temperature != nil && volume != nil && moles != nil {
            calculatedPressure = (calculatedMoles * R * calculatedTemperature) / calculatedVolume
        } else if temperature == nil && pressure != nil && volume != nil && moles != nil {
            calculatedTemperature = (calculatedPressure * calculatedVolume) / (calculatedMoles * R)
        } else if volume == nil && pressure != nil && temperature != nil && moles != nil {
            calculatedVolume = (calculatedMoles * R * calculatedTemperature) / calculatedPressure
        } else if moles == nil && pressure != nil && temperature != nil && volume != nil {
            calculatedMoles = (calculatedPressure * calculatedVolume) / (R * calculatedTemperature)
        }
        
        return .gasLaws(pressure: calculatedPressure, volume: calculatedVolume, temperature: calculatedTemperature, moles: calculatedMoles)
    }
    
    func calculatepH(hydrogenConcentration: Double?, hydroxideConcentration: Double?, acidConcentration: Double?) -> ChemistryCalculationResult {
        var pH = 7.0
        var pOH = 7.0
        
        if let hConc = hydrogenConcentration, hConc > 0 {
            pH = -log10(hConc)
            pOH = 14 - pH
        } else if let ohConc = hydroxideConcentration, ohConc > 0 {
            pOH = -log10(ohConc)
            pH = 14 - pOH
        } else if let acidConc = acidConcentration, acidConc > 0 {
            // Assuming strong acid
            pH = -log10(acidConc)
            pOH = 14 - pH
        }
        
        let isAcidic = pH < 7
        
        return .pH(pH: pH, pOH: pOH, isAcidic: isAcidic)
    }
    
    func calculateStoichiometry(reactants: String, products: String, mass: Double) -> ChemistryCalculationResult {
        let limitingReactant = determineLimitingReactant(reactants: reactants)
        let theoreticalYield = calculateTheoreticalYield(products: products, mass: mass)
        let percentYield = calculatePercentYield(actual: theoreticalYield * 0.85, theoretical: theoreticalYield)
        
        return .stoichiometry(limitingReactant: limitingReactant, theoreticalYield: theoreticalYield, percentYield: percentYield)
    }
    
    // MARK: - Helper Methods
    private func parseChemicalFormula(_ formula: String) -> (mass: Double, composition: String) {
        var totalMass = 0.0
        var composition = ""
        var i = 0
        
        while i < formula.count {
            let index = formula.index(formula.startIndex, offsetBy: i)
            let char = String(formula[index])
            
            if isUppercaseLetter(char) {
                var element = char
                var numberStr = ""
                i += 1
                
                // Check for lowercase letters
                while i < formula.count {
                    let nextIndex = formula.index(formula.startIndex, offsetBy: i)
                    let nextChar = String(formula[nextIndex])
                    if isLowercaseLetter(nextChar) {
                        element += nextChar
                        i += 1
                    } else {
                        break
                    }
                }
                
                // Check for numbers
                while i < formula.count {
                    let nextIndex = formula.index(formula.startIndex, offsetBy: i)
                    let nextChar = String(formula[nextIndex])
                    if isNumber(nextChar) {
                        numberStr += nextChar
                        i += 1
                    } else {
                        break
                    }
                }
                
                let count = Double(numberStr.isEmpty ? "1" : numberStr) ?? 1.0
                let atomicMass = atomicMasses[element] ?? 0.0
                let elementMass = atomicMass * count
                totalMass += elementMass
                
                composition += "\(element): \(count) atoms, \(String(format: "%.2f", elementMass)) g/mol\n"
            } else {
                i += 1
            }
        }
        
        return (totalMass, composition)
    }
    
    private func isUppercaseLetter(_ char: String) -> Bool {
        return char.range(of: "[A-Z]", options: .regularExpression) != nil
    }
    
    private func isLowercaseLetter(_ char: String) -> Bool {
        return char.range(of: "[a-z]", options: .regularExpression) != nil
    }
    
    private func isNumber(_ char: String) -> Bool {
        return char.range(of: "[0-9]", options: .regularExpression) != nil
    }
    
    private func balanceEquation(reactants: String, products: String) -> String {
        // Simplified balancing - in a real app, this would be more complex
        return "2\(reactants) → 2\(products)"
    }
    
    private func determineReactionType(reactants: String, products: String) -> String {
        if reactants.contains("O2") && products.contains("H2O") {
            return "Combustion"
        } else if reactants.contains("+") && products.contains("+") {
            return "Double Displacement"
        } else if reactants.contains("H") && products.contains("H2") {
            return "Single Displacement"
        } else {
            return "Synthesis"
        }
    }
    
    private func determineLimitingReactant(reactants: String) -> String {
        // Simplified limiting reactant determination
        let components = reactants.components(separatedBy: "+")
        return components.first?.trimmingCharacters(in: .whitespaces) ?? "Unknown"
    }
    
    private func calculateTheoreticalYield(products: String, mass: Double) -> Double {
        // Simplified theoretical yield calculation
        return mass * 1.2 // Assume 20% increase
    }
    
    private func calculatePercentYield(actual: Double, theoretical: Double) -> Double {
        return (actual / theoretical) * 100
    }
}

// MARK: - Supporting Types
enum ChemistryCalculationResult {
    case molarMass(formula: String, mass: Double, composition: String)
    case reaction(reactants: String, products: String, balanced: String, type: String)
    case concentration(molarity: Double, molality: Double, normality: Double)
    case gasLaws(pressure: Double, volume: Double, temperature: Double, moles: Double)
    case pH(pH: Double, pOH: Double, isAcidic: Bool)
    case stoichiometry(limitingReactant: String, theoreticalYield: Double, percentYield: Double)
}
690 lines•26.9 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