Swift - 解析字符串中的数学运算 [英] Swift - Resolving a math operation in a string
问题描述
只是一个简短的问题.在 Swift 中可以解决以下代码:
just a short question. In Swift it is possible to solve the following code:
var a: String;
a = "\(3*3)";
将解决字符串中的算术运算.但我无法弄清楚,为什么以下变化不起作用.
The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work.
var a: String;
var b: String;
b = "3*3";
a = "\(b)";
在这种情况下,var a 中的算术运算将不会被解析.任何想法为什么以及如何我可以开始工作.如果这行得通,有些事情会容易得多.感谢您的回答.
In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers.
推荐答案
在第二种情况下,您插入的是字符串,而不是算术表达式.在您的示例中,它是您在编译时选择的字符串,但通常它可能是来自用户的字符串,也可能是从文件或网络加载的字符串.换句话说,在运行时 b
可以包含一些任意字符串.编译器在运行时无法将任意字符串解析为算术.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b
could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic.
如果你想在运行时将任意字符串计算为算术公式,你可以使用 NSExpression
.这是一个非常简单的例子:
If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression
. Here's a very simple example:
let expn = NSExpression(format:"3+3")
println(expn.expressionValueWithObject(nil, context: nil))
// output: 6
您还可以使用第三方库,例如 DDMathParser
.
You can also use a third-party library like DDMathParser
.
这篇关于Swift - 解析字符串中的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!