作者:CC周兵价_667 | 来源:互联网 | 2023-05-18 15:54
我有一个变量,我有一个函数作为字符串存储在其中:
var x = "func myFunction(y :Int) {println(y)}"
有没有办法评估字符串并运行函数?
1> AstroCB..:
没有.
Swift中没有eval()
Javascript或ScriptEngine
Java的等价物.
字符串评估的一个常见用途是数学表达式; 如果你想评估这些,你可以使用NSExpression.valueWithExpression(format: String)
:
let stringWithMathematicalOperation: String = "5*5" // Example
let exp: NSExpression = NSExpression(format: stringWithMathematicalOperation)
let result: Double = exp.expressionValueWithObject(nil, context: nil) as Double // 25.0