Swift – Resolving a math operation in a string

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.

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

You can also use a third-party library like DDMathParser.

Leave a Comment