Michael Stern
Michael Stern

Reputation: 487

Swift - conversion of string to expression

I am working on an application in which simple mathematical expressions are passed around as strings (for example "2+3"). I need to execute these expressions to make sure they equal a target.

In Mathematica / Wolfram Language, one can convert strings to expressions with the simple command ToExpression[]. Is there anything equivalent in Swift? If not, how might one convert the string into workable math?

Upvotes: 1

Views: 2034

Answers (1)

timgcarlson
timgcarlson

Reputation: 3146

Use [NSExpression][1], like this...

let expression = NSExpression(format:"2+3")
if let result = expression.expressionValueWithObject(nil, context: nil) as? NSNumber {
  print(result)
} else {
  print("error evaluating expression")
}

Here's a good blog post from NSHipster on using NSExpression (includes Swift examples).

Upvotes: 4

Related Questions