7

I use NSExpression to solve math formulas. Everthing works fine, if the input formula is correct, but if I input a formula like:

6-

My app gets terminated with the following error message:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "6- == 1"'

In Object-C it is possible to put this code into a @try block. Is there something equal in swift? Or how do I handle this Exceptions?

Here is my simple NSExpression code:

let expression = NSExpression(format: finalFormula)

if let result = expression.expressionValueWithObject(nil, context: nil) as? NSNumber {
    return result
}

I solution would be to check the input first, but I would be OK for me if I get back nil or something like this.

patrickS
  • 3,010
  • 3
  • 23
  • 38
  • Same question here: http://stackoverflow.com/questions/24710424/catch-an-exception-for-invalid-user-input-in-swift. It seems that a syntax error in the expression cannot be catched in Swift. – Martin R Jan 17 '15 at 23:50
  • 1
    So it looks like I have to validate the input value first? – patrickS Jan 18 '15 at 07:23
  • @patrickS were you able to find a proper solution other than manually validating the input yourself? – Craig Aug 12 '16 at 05:00

0 Answers0