Check expression is valid or not

谁都会走 提交于 2019-12-02 17:16:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54977853/check-expression-is-valid-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!