Check expression is valid or not

前端 未结 1 1973
甜味超标
甜味超标 2021-01-27 17:43

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

I

1条回答
  •  忘了有多久
    2021-01-27 18:01

    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
    

    0 讨论(0)
提交回复
热议问题