1

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

I want to validate expression is valid or not. And I am trying this using following code :

let equationString = "12+6+"

do {
    let expr =  try NSExpression(format: equationString)
    if let result = expr.expressionValue(with: nil, context: nil) as? NSNumber {
        let x = result.doubleValue
        print(x)
    } else {
        print("failed")
    }
}
catch {
    print("failed")
}

I have used try-catch statement, but still I am getting crash here. Is there any solution for this?

Any help would be appreciated.

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
  • 1
    I've tried founding a solution in vain... But I did found a lot of topics covering the subject like this one: https://stackoverflow.com/questions/43585508/correct-way-to-catch-nsinvalidargumentexception-when-using-nsexpression It looks like the solution is to use another language because swift just doesn't handle it (the string passed into NSExpression constructor have to be valid, or it will crash anyway), or maybe there is a library that can do the job for you. – Alexis Mar 04 '19 at 15:59

1 Answers1

5

And you can use it with try:

let equationString = "12+6+"//"12*/6+10-5/2"

do {
    try TryCatch.try({
        let expr = NSExpression(format: equationString)
        if let result = expr.expressionValue(with: nil, context: nil) as? NSNumber {
            let x = result.doubleValue
            print(x)
        } else {
            print("failed")
        }
    })
} catch {
    print("Into the catch.....")
    // Handle error here
}

TryCatch.h:

+ (BOOL)tryBlock:(void(^)(void))tryBlock
           error:(NSError **)error;

TryCatch.m:

@implementation TryCatch

+ (BOOL)tryBlock:(void(^)(void))tryBlock
           error:(NSError **)error
{
    @try {
        tryBlock ? tryBlock() : nil;
    }
    @catch (NSException *exception) {
        if (error) {
            *error = [NSError errorWithDomain:@"com.something"
                                         code:42
                                     userInfo:@{NSLocalizedDescriptionKey: exception.name}];
        }
        return NO;
    }
    return YES;
}

@end
Meet Doshi
  • 4,241
  • 10
  • 40
  • 81