创建计算器历史数组swift

时间:2017-04-13 00:34:10

标签: ios

我创建了一个计算器并创建了一个Model.swift来处理我的所有计算。然后在我的ViewController.swift中处理其他所有内容。我正在尝试添加其他功能,我希望创建一个在我的计算器中执行的所有操作的历史记录,并将它们存储在一个数组中。

到目前为止,这是我的代码:

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var displayLabel: UILabel!
    @IBOutlet weak var HistoryLabel: UILabel!

    var historyArray: [String] = []
    var userIsTypingNumbers = false
    var firstNumber = 0
    var secondNumber = 0

    @IBAction private func NumbersEntered(_ sender: UIButton) {
        //know what number is being pressed
        /*let digit = sender.currentTitle!
        //if user is typing a number, do this.
        if userIsTypingNumbers{
            //specify what number is being pressed
            let textCurrentDisplay = displayLabel.text!
            //append the another number onto the previous number.
            displayLabel.text = textCurrentDisplay + digit
        } else {
            displayLabel.text = digit
        }
        userIsTypingNumbers = true*/
        /*addToHistory(recordToAddToHistory: digit)*/
        let number = sender.currentTitle

        if userIsTypingNumbers {
            displayLabel.text = displayLabel.text! + number!
        } else {
            displayLabel.text = number
            userIsTypingNumbers = true
        }
    }
    var displayValue: Double {

        get {
            return Double(displayLabel.text!)!
        }
        set {
            displayLabel.text = String(newValue)
        }
    }

    private var calculations = PerformCalculations()

    @IBAction func Enter(_ sender: UIButton) {
        //perform the calculations
        if userIsTypingNumbers{
            calculations.setOperand(operand: displayValue)
            userIsTypingNumbers = false
        }
        if let mathematicalSymbol = sender.currentTitle {
            calculations.performOperation(symbol: mathematicalSymbol)
            /*addToHistory(recordToAddToHistory: String(mathematicalSymbol))*/
        }
        /*HistoryLabel.text = HistoryLabel.text! + String(sender.currentTitle!)*/
        displayValue = calculations.result
        /*HistoryLabel.text = HistoryLabel.text! + String(displayValue)*/
        /*historyArray.append("\(String(describing: HistoryLabel.text))")*/
    }


    @IBAction func Clear(_ sender: UIButton) {
        //clear display to 0.
        displayLabel.text = "0"
        HistoryLabel.text = ""
    }

    @IBAction func Delete(_ sender: UIButton) {
        //deleting last typed number, if user messed up.
        let name: String = self.displayLabel.text!
        //count number of characters.
        let stringLength = name.characters.count
        let substringIndex = stringLength - 1
        displayLabel.text = (name as NSString).substring(to: substringIndex)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "History"){
            if let destinationVC = segue.destination as? HistoryClassViewController{
                destinationVC.someData = HistoryLabel.text
            }
        }
    }*/
}

Model.swift

import Foundation

enum Optional<T>{
    case None
    case Some(T)
}

class PerformCalculations {

    private var accumulator = 0.0

    func setOperand(operand: Double){
        accumulator = operand
    }
    //performing the operations for various operands
    private var operations: Dictionary<String, Operation> = [
        "√" : Operation.UnaryOperation(sqrt), //sqrt,
        "×": Operation.BinaryOperation({$0 * $1}),
        "+": Operation.BinaryOperation({$0 + $1}),
        "-": Operation.BinaryOperation({$0 - $1}),
        "÷": Operation.BinaryOperation({$0 / $1}),
        "=": Operation.Equals
    ]
    //case for various operands
    private enum Operation{
        case Constant(Double)
        case UnaryOperation((Double) -> Double)
        case BinaryOperation((Double, Double) -> Double)
        case Equals
    }
    //switch case to actually perform the operations
    func performOperation(symbol: String){
        if let operation = operations[symbol]{
            switch operation{
            case .Constant(let value): accumulator = value
            case .BinaryOperation(let function):
                executePendingBinaryOperation()
                pendingVar = PendingBianryOperationInfo(binaryFunction: function, firstOperand: accumulator)
            case .UnaryOperation(let foo): accumulator = foo(accumulator)
            case .Equals:
                executePendingBinaryOperation()
            }
        }
    }
    private func executePendingBinaryOperation(){
        if pendingVar != nil{
            accumulator = pendingVar!.binaryFunction(pendingVar!.firstOperand,accumulator)
            pendingVar = nil
        }
    }

    private var pendingVar: PendingBianryOperationInfo?

    private struct PendingBianryOperationInfo{
        var binaryFunction: (Double, Double) -> Double
        var firstOperand: Double
    }

    var result: Double{
        get{
            return accumulator
        }
    }
}

非常感谢任何帮助,非常感谢!

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题。这是更新的代码,因为它对某人来说非常方便。

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var displayLabel: UILabel!
    @IBOutlet weak var HistoryLabel: UILabel!

    var historyArray: [String] = []
    var userIsTypingNumbers = false
    var firstNumber = 0
    var secondNumber = 0
    var operation = ""
    var result = 0.0

    @IBAction private func NumbersEntered(_ sender: UIButton) {

        //know what number is being pressed
        let number = sender.currentTitle
        //if user is typing number, do this.
        if userIsTypingNumbers {
            //specify what number is being pressed.
            //append the number onto the previous number.
            displayLabel.text = displayLabel.text! + number!
        } else {
            displayLabel.text = number
            userIsTypingNumbers = true
        }
    }
    var displayValue: Double {

        get {
            return Double(displayLabel.text!)!
        }
        set {
            displayLabel.text = String(newValue)
        }
    }

    private var calculations = PerformCalculations()


    @IBAction func OperationsPressed(_ sender: UIButton) {
        userIsTypingNumbers = false
        firstNumber = Int(Double(displayLabel.text!)!)
        operation = sender.currentTitle!
        if operation == "√" {
            result = (PerformCalculations().squareroot(a: Double(firstNumber)))
            displayLabel.text = String(result)
        }
    }


    @IBAction func Enter(_ sender: UIButton) {
        userIsTypingNumbers = false
        secondNumber = Int(Double(displayLabel.text!)!)


        if operation == "+" {
            result = (PerformCalculations().add(a: Double(firstNumber), b: Double(secondNumber)))
        } else if operation == "÷" {
            result = (PerformCalculations().division(a: Double(firstNumber), b: Double(secondNumber)))
        } else if operation == "×" {
            result = (PerformCalculations().multiplication(a: Double(firstNumber), b: Double(secondNumber)))
        } else if operation == "-" {
            result = (PerformCalculations().subtract(a: Double(firstNumber), b: Double(secondNumber)))
        }
        displayLabel.text = String(result)

        historyArray.append("\(firstNumber) \(operation) \(secondNumber) = \(result)")
        userIsTypingNumbers = false

        //self.performSegue(withIdentifier: "History", sender: self)

    }


    @IBAction func Clear(_ sender: UIButton) {
        //clear display to 0.
        displayLabel.text = "0"
    }

    @IBAction func Delete(_ sender: UIButton) {
        //deleting last typed number, if user messed up.
        let name: String = self.displayLabel.text!
        //count number of characters.
        let stringLength = name.characters.count
        let substringIndex = stringLength - 1
        displayLabel.text = (name as NSString).substring(to: substringIndex)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "History" {
            if let destinationVC = segue.destination as? TableTableViewController {
                destinationVC.dataString = historyArray.description
            }
        }
    }*/

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destViewController : TableTableViewController = segue.destination as! TableTableViewController

        destViewController.dataString = historyArray.description

    }
}

Model.swift

import Foundation


class PerformCalculations {

    func add(a: Double, b: Double) -> Double {
        let result = a + b
        return result
    }
    func division(a: Double, b: Double) -> Double {
        let result = a / b
        return result
    }
    func subtract(a: Double, b: Double) -> Double {
        let result = a - b
        return result
    }
    func multiplication(a: Double, b: Double) -> Double {
        let result = a * b
        return result
    }
    func squareroot(a: Double) -> Double {
        let result = sqrt(a)
        return result
    }
}