本文介绍了检查表达式是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要验证表达式是否有效.我正在尝试使用以下代码:
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")
}
我使用了try-catch语句,但是仍然在这里崩溃.有什么解决办法吗?
I have used try-catch statement, but still I am getting crash here. Is there any solution for this?
任何帮助将不胜感激.
推荐答案
您可以尝试使用它:
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
这篇关于检查表达式是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!