Mukesh N
Mukesh N

Reputation: 71

Evaluating values in NSExpression

I'm using NSExpression for evaluating the following operation. But i'm getting NSInvalidArgumentException error for this. Please let me know how to evaluate the following operation.Thanks in Advance

  let formula:NSString = "((y*4)⁄5)"
    formula=formula.stringByReplacingOccurrencesOfString("y", withString: "8")
    let expression = NSExpression(format: formula as String)
    if let convertedValue = expression.expressionValueWithObject(nil, context: nil) as? NSNumber {
        formula=NSNumber(float:convertedValue.floatValue).stringValue
       }

Upvotes: 2

Views: 806

Answers (1)

AlexT
AlexT

Reputation: 616

A bit late but here goes for the benefit of others. formula should be a var as you mutate it, but presumably that was a copying error, or your code would never have compiled.

I copied your code into a playground and got similar errors, but only with expressions got by the replacing method. Inspecting the strings character by character I've finally twigged that your "/" is something different. See the difference? / ⁄. I've updated it for Swift 3; there seemed a lot of awkward type converting!

var formula = "y*4/5"
//"((y*4)⁄5)" : what you had, brackets were superfluous but ok
formula = formula.replacingOccurrences(of: "y", with: "8")    

let expression: NSExpression = NSExpression(format: formula)

if let convertedValue = expression.expressionValue(with: nil, context: nil) {
  let formula = String(convertedValue as! Float)
  print(formula)
}

Note that you get an integer answer. If you want a real result you'll have to add '.0' to one of the operands.

Upvotes: 0

Related Questions