我试图复制需要在Swift 中的Objective-C中编写计算器但我的代码不起作用.
import Foundation
var equation:NSString = "5*(2.56-1.79)-4.1"
var result = NSExpression(format: equation, argumentArray: nil)
println(result)
Run Code Online (Sandbox Code Playgroud) 我想验证用户创建的表达式(如“2+2”、“5+7”或更复杂的)。我使用 NSExpression 类来解析和计算这个表达式。这是我的游乐场代码:
import UIKit
let string = "2+2"
var ex:NSExpression?
do {
ex = NSExpression(format: string)
}
catch {
print("String is not valid expression")
}
if let result = ex?.expressionValue(with: nil, context: nil) as! NSNumber? {
print("result is \(result)")
}
Run Code Online (Sandbox Code Playgroud)
当我使用有效表达式(“2+2”)时 - 我得到了结果。但有时用户可能会提供错误的字符串(例如“2+”)。有了这个字符串,我的应用程序崩溃了:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "2+ == 1"'
Run Code Online (Sandbox Code Playgroud)
我不明白我如何捕捉这个异常以及为什么上面的代码不这样做。现在我使用 Objective C 类(具有相同的逻辑),从我的 swift 代码中调用这个方法,在那个类中我真的可以捕获这样的异常:
+(NSNumber *)solveExpression:(NSString *)string
{
id value;
@try {
NSExpression *ex = [NSExpression …
Run Code Online (Sandbox Code Playgroud) exception-handling nsexpression swift objective-c-swift-bridge