Can you evaluate a string in Swift?
Asked Answered
H

2

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?

Humid answered 11/3, 2015 at 0:34 Comment(0)
H
29

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
Hotheaded answered 11/3, 2015 at 0:44 Comment(3)
This does crash when you perform mod operation. 10%20 it will crash.Persuasion
I am trying to use that for formulas, but when I divide multiply and power it gives me a strange number that don’t correspond to the correct resultGob
My problem was related with the comma format, after change it everything works great.Gob
P
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
Pfeifer answered 11/12, 2019 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.