Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you evaluate a string in Swift?

I have a variable and I have a function stored in it as a string:

var x = "func myFunction(y :Int) {println(y)}"

Is there a way to evaluate the string and run the function?

like image 500
Krncy Avatar asked Mar 11 '15 00:03

Krncy


1 Answers

No.

There is no equivalent of eval() in JavaScript or ScriptEngine in Java for Swift.

A common use for string evaluation is mathematical expressions; if you want to evaluate these, you can use NSExpression.valueWithExpression(format: String):

let stringWithMathematicalOperation: String = "5*5" // Example
let exp: NSExpression = NSExpression(format: stringWithMathematicalOperation)
let result: Double = exp.expressionValue(with:nil, context: nil) as! Double // 25.0
like image 172
AstroCB Avatar answered Oct 22 '22 11:10

AstroCB