由于未捕获的异常而终止应用程序 “ NSInvalidArgumentException”,原因:“无法解析格式 字符串“ 12 + 6 + == 1”'
我要验证表达式是否有效。我正在尝试使用以下代码:
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")
}
我使用了try-catch语句,但是仍然在这里崩溃。有什么解决办法吗?
任何帮助将不胜感激。
答案 0 :(得分:0)
您可以尝试使用它:
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