如何在 swift 中将存储在变量中的字符串转换为可执行代码文本?



我一直在尝试在 xcode 9 中开发一个功能正常的计算器(现在看来是徒劳的),但我需要以某种方式将字符串转换为代码文本文件。这是我的视图控制器文件(为非常草率和杂乱无章的代码道歉......

import UIKit
class ViewController: UIViewController {
var calculation_string : String = ""
var displayed = "0"
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.
}
@IBOutlet weak var calc_display: UILabel!
@IBAction func button_pressed(_ sender: UIButton) {
calc_display.text = "asdf"
print(sender.tag)
calculation_string = calculation_string + String(identify(btn_tag: sender.tag))
print(calculation_string)
print(identify(btn_tag: sender.tag))
}

//1-receive and identify the data submitted.
//2-append the string used for calculations from either end; or delete it alltogether depending on the button pressed.
//display on the display area.
func identify(btn_tag: Int) -> String {
if btn_tag == 1 {
return "1"
}
if btn_tag == 2 {
return "2"
}
if btn_tag == 3 {
return "3"
}
if btn_tag == 4 {
return "4"
}
if btn_tag == 5 {
return "5"
}
if btn_tag == 6 {
return "6"
}
if btn_tag == 7 {
return "7"
}
if btn_tag == 8 {
return "8"
}
if btn_tag == 9 {
return "9"
}
if btn_tag == 10 {
return "0"
}
if btn_tag == 11 {
return "."
}
if btn_tag == 13 {
return "+"
}
if btn_tag == 14 {
return "-"
}
if btn_tag == 15 {
return "*"
}
if btn_tag == 16 {
return "/"
}
if btn_tag == 17 {
return "*(0.01)"
}
else {
return ""
}
}
func change_sign() {
calculation_string = "-(" + calculation_string + ")"
}
func equals() {
//makes the value displayed equal to the calculation string
//or returns 'error' if the statement makes no sense or is erroneous.
}
func reset() {
calculation_string = ""
}

}

我需要将此"calculation_string"变量转换为代码,以便我可以执行计算,然后使用"显示"变量显示它。有谁知道如何做到这一点?

如果有人考虑评估和批评我的代码,并提出其他有效的方法,我也会同样高兴。再次为正在进行的代码的草率表示歉意。

干杯!

Swift 没有像 Lisp 那样的eval函数。你不能创建一堆 Swift 代码作为字符串,然后在运行时执行它。相反,您需要自己解析字符串并对其进行评估。

这不是微不足道的,但 Nick Lockwood 创建了一个非常漂亮的库,叫做 Expression 来做到这一点。您不必使用该库,但它很好地介绍了如何解决问题。它大约有 1500 行 Swift,你可以以一种非常简单的方式研究它如何标记和评估字符串。(它有一些性能优化,如果没有它可能会更容易理解,但我仍然希望你可以通过一些工作来完成你的工作。

如果你想从头开始构建这种东西,通常首先探索构建RPN(反向波兰符号)计算器。这是一个基于堆栈的计算器,通常比"中缀"计算器更容易实现。而不是1 + 2输入1 2 ++始终使用堆栈上的最后两个值。如果你想进入解析器和评估器,RPN 是一个很好的起点。实现起来要简单得多。

还有内置的NSExpression可以为你做到这一点,并且是内置的,但是在 Swift 中使用起来很痛苦,我真的不推荐它,除非你只需要一些非常快速的东西。

您可能正在寻找 NSExpression,它之所以可用,是因为您已经导入了 Foundation 和/或 UIKit。已经有很多关于基于NSExpression构建的计算器的讨论 堆栈溢出;例如:

Swift 中的 NSExpression calculator

相关内容

最新更新