在swift中计算数组编号输入?

时间:2017-11-17 10:08:48

标签: arrays swift xcode calculator

所以这就是我对代码走了多远。一切正常,但我还不知道如何继续前进。我现在需要做的是进行计算过程并将其打印在文本字段中。我有想法在视图控制器类中使用数学部分并使用字符串数字,但我想看看你是否可以使用数组中的数字。

这是操作的类:

import Foundation
import UIKit


class Calculation {

    var operation: String = ""
    var numbers: [Int] = []


    func operationInput() {

        switch operation {    // I still haven't figured out how to write the math part of it with array numbers.
        case "+":
            break
        case "-":
            break
        case "*":
            break
        case "/":
            break
        default:
            break
        }
    }
}

这是我的主视图控制器:

    import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var resultLabel: UILabel!
    var numbers: String = ""
    var calculation = Calculation()
    var finalNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func acPressed(_ sender: UIButton) {
        resultLabel.text = "0"
        numbers = ""
    }

    @IBAction func numberPressed(_ sender: UIButton) {

        let number = sender.titleLabel?.text
        numbers.append(number!)
        print(numbers)
        resultLabel.text = numbers

    }

    @IBAction func operationPressed(_ sender: UIButton) {

        let operationInput = sender.title(for: .normal)!
        calculation.numbers.append(Int(numbers)!)
        print(operationInput)
        print(calculation.numbers[0])
        numbers = ""
        resultLabel.text = calculation.operation
    }

    @IBAction func equationOperator(_ sender: UIButton) {

        let equation = sender.title(for: .normal)!
        if equation == "=" {
            finalNumber = Int(numbers)!
            resultLabel.text = "\(finalNumber)"
        }
    }

}

1 个答案:

答案 0 :(得分:0)

或者您可以使用2个不同的变量来简化事情,第3个变量可以将结果存储在