Mee*_*shi 1 math try-catch nsexpression swift4
由于未捕获的异常“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")
}
Run Code Online (Sandbox Code Playgroud)
我已经使用了 try-catch 语句,但仍然在这里崩溃。有什么解决办法吗?
任何帮助,将不胜感激。
你可以尝试使用它:
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
}
Run Code Online (Sandbox Code Playgroud)
TryCatch.h:
+ (BOOL)tryBlock:(void(^)(void))tryBlock
error:(NSError **)error;
Run Code Online (Sandbox Code Playgroud)
尝试捕获.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
Run Code Online (Sandbox Code Playgroud)