对于Swift中的计算器 [英] For Calculator in Swift

查看:133
本文介绍了对于Swift中的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅会警告您,我是新手,所以我仍然习惯于它的工作方式.我一直在尝试上这个计算器项目.问题是,我需要练习简化代码.

Just gonna warn you, I'm brand new to swift and I'm still getting used to how this works. I've been trying to work on this Calculator project for class. The problem is, I need practice simplifying code.

现在,当按下数字按钮时,我将其保存在这样的数组中.

Right now, when a number button is pressed, I have it saved in an array like this.

@IBAction func buttonPressed(_ sender: UIButton) {
    if numBtnPressed == true {
    numArray.append(sender.title(for: .normal)!)
    }
 }

因此,如果按下标记为1的按钮,它将["1"]作为字符串存储在空数组numArray中

so if the button labeled 1 is pressed, it stores ["1"] as a string in the empty array numArray

在需要时,我为操作员提供了一个单独的结构.

I have a separate structure for operators in case I need it.

struct calcFuncs {
  var add : String
  var subtract : String
  var divide : String
  var multiply : String
}
  var calc = calcFuncs(add: "+", subtract: "-", divide: "/", multiply: "x")

我试图弄清楚如何拥有一串数字和运算符(例如1 + 2 x 3 + 4/5 + 5),并让编译器保存该计算,然后在按下equal时将其打印出来.我知道即使现在所有内容都在一个字符串中,我也必须找到一种方法来完成计算.我希望它在标签上打印完成的字符串.

I'm trying to figure out how to have a string of numbers and operators (example 1 + 2 x 3 + 4 / 5 + 5) and have the compiler save that calculation, then print it when equal is pressed. I know I have to find a way to have calculations done even though everything is in a string right now. I want it to print the finished string on a label.

我坚持如何从数组中提取项目,并根据单击的运算符在运算符之间出现一个运算符. ("[1](操作员)[2](操作员)[3](操作员)",然后打印总和.

I'm stuck on how to pull the items from the array and have an operator appear inbetween depending on what operator was clicked. ("[1] (operator) [2] (operator) [3] (operator)") and have it print a sum.

我在想这样的事情,但我知道它很乏味,可能无法正常工作:

I was thinking something like this but I know its tedious and probably won't work:

  for 0...1 in index:
      [0] something [1]
      1...2 in index:
      etc etc

我知道这听起来很疯狂,但是我正在努力告诉计算机我想要什么(按下这些按钮时计算一串数字,保存总数,然后在单击等于时打印总数),然后将其整理干净-剪切代码.

I know this sounds insane, but I'm struggling telling the computer what I want (calculate a string of numbers when these buttons are pressed, save the total, then print total when equal is clicked) and putting that into clean-cut code.

任何建议,即使它意味着更改我的所有代码,也应受到赞赏.

Any advice at all, even if it means changing all my code, is appreciated.

推荐答案

您有一些好主意,但也许有一种更简单的方法.本示例使用可以在Interface Builder中设置的按钮的tag属性以及NSExpression类来评估数学.还有许多其他方法可以做到这一点.

You have some good ideas, but perhaps there is an easier way. This example uses the tag property of buttons that you can set in Interface Builder, and the NSExpression class to evaluate the maths. There are many other ways to do it.

这将遵循标准的运算顺序(例如,加法和减法之前的乘法和除法).

This will follow the standard order of operations (multiplication and division before addition and subtraction, for example).

import UIKit

var calculationString = "" // Declare this outside method in view controller

@IBAction func buttonPressed(_ sender: UIButton) {
    // Use the tag property of buttons which can be set in Interface Builder
    // Number buttons can have tag values 0-9
    // Operator buttons can have higher tag numbers (10: "+", 11: "-", 12: "*" 13: "/")
    // Decimal point button tag (14)
    // Calculate or equals button tag (15)
    // Check for tag number

    switch sender.tag {
    case 0...9:
        // Numbers
        calculationString.append(String(sender.tag))
    case 10:
        // Add
        calculationString.append("+")
    case 11:
        // Subtract
        calculationString.append("-")
    case 12:
        // Multiply
        calculationString.append("*") // Need to use asterisk for multiply
    case 13:
        // Divide
        calculationString.append("/")
    case 14:
        // Decimal
        calculationString.append(".")
    case 15:
        // Perform calculation
        let expression = NSExpression(format: calculationString)
        let result = expression.expressionValue(with: nil, context: nil) ?? 0
        yourLabel.text = "Result: \(result)" // Or do whatever you need with the result.
    default:
        fatalError("Unknown button tag")
    }
    yourLabel.text = calculationString // Display user input if desired
}

这篇关于对于Swift中的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆