检查表达式是否有效
Check expression is valid or not
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Unable to parse the format
string "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 语句,但我仍然在这里崩溃。有解决办法吗?
如有任何帮助,我们将不胜感激。
你可以尝试使用它:
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
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "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 语句,但我仍然在这里崩溃。有解决办法吗?
如有任何帮助,我们将不胜感激。
你可以尝试使用它:
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