-2

So, I've been making a basic calculator. But I've run into an issue. My code.

@IBAction func calculate(_ sender: UIButton) {
    let stringExpression = resultLabel.text!
    let expression = NSExpression(format: stringExpression)
    let result = expression.expressionValue(with: nil, context: nil) as! NSNumber
    resultLabel.text! = String(result.doubleValue) // Writes response on textLabel :D
}     

The code above works. However, when a input such as 5++6 is entered it crashes my app. I'm not very sure how to deal with this.

The following error is shown when a invalid input is entered. The error given. libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

I'm not sure how I could make it display "Error". And this should work for any type of error.

Krunal
  • 68,602
  • 40
  • 230
  • 241
  • 2
    Copy/paste code or error message, do not show screenshots. – Larme Aug 31 '17 at 13:59
  • Fixed :) @Larme – Pranav Ramesh Aug 31 '17 at 14:05
  • 1
    And there is no explicit error message? Because I tried your code and got the real (and useful message): "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "5++6 == 1"'" And it happens on "let expression = NSExpression(format: stringExpression)". That's real information to read and give about your issue. – Larme Aug 31 '17 at 14:11
  • Possible duplicate of [Catch an exception for invalid user input in swift](https://stackoverflow.com/questions/24710424/catch-an-exception-for-invalid-user-input-in-swift) – Larme Aug 31 '17 at 14:15
  • That duplicate is for Swift 2. – Pranav Ramesh Aug 31 '17 at 14:16
  • @PranavRamesh The gist ist still true: You can't catch objc exceptions in swift. Use an objc wrapper that exposes standard objc error handling, usable in swift with do/try/catch. – Nikolai Ruhe Aug 31 '17 at 14:28

1 Answers1

0

You have to pass a valid expression to the NSExpression initialiser or else it will throw an exception. There is no Swift-only way to catch exceptions so the only possibility for you is to make sure only valid input can be generated.

Tom E
  • 1,302
  • 5
  • 14