-3

I am building a Calculator app which uses a parser that is called DDMathParser. It can evaluate a string such as "2+3-1" and outputs 4 as the answer. However, if I put something like "3+++3" or "log5" instead of log(5), the app crashes which is expected (the error message is like "invalid format: blah blah blah... fatal error: unexpectedly found nil while unwrapping an Optional value." I am wondering if there is a way to handle these kind of error to prevent the app from crashing? I mean if the user input "3++++3", the app will output an error message on a textview box or nothing, as long as it doesn't crash the app... Thanks in advance!

Edit: The code is "str.numberByEvaluatingString().doubleValue" where str is a string like "3+(2-4)" or "ln(3)" etc... and numberByEvaluatingString() is a function from DDMathParser. If I input the correct format (i.e. 3+2, ln(5)), it will give me the correct result, however, if I input some string like 3+++3, or ln5 without the bracket, it will crash...

j259liu
  • 1
  • 1

1 Answers1

0

Try

if let num = str.numberByEvaluatingString() {
    let value = num.doubleValue
} else {
    // Handle error here
}
Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65