2

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
       }
Mukesh N
  • 71
  • 1
  • 8

1 Answers1

0

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.

AlexT
  • 596
  • 7
  • 15