9

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?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Krncy
  • 93
  • 1
  • 3

2 Answers2

28

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
Shaheen Ghiassy
  • 7,397
  • 3
  • 40
  • 40
AstroCB
  • 12,337
  • 20
  • 57
  • 73
0

Yes, and if string contains boolean expression then also this can be evaluated. I've done it something like this,

let stringWithMathematicalOperation: String = "true && false "
let exp: NSExpression = NSExpression(format: stringWithMathematicalOperation)
let result: Bool = exp.expressionValueWithObject(nil, context: nil) as Bool // Answer: false
Niki
  • 1,566
  • 1
  • 19
  • 36