我正在尝试这个计算器代码.如何处理无效的用户输入?
//答案:将标题桥接到Objective-C // https://github.com/kongtomorrow/TryCatchFinally-Swift
这是同样的问题,但在objc但我想在swift中这样做.从NSExpression捕获NSInvalidArgumentException
我想要显示的只是一条消息,如果它不起作用,但现在当用户没有输入正确的格式时我得到一个例外.
import Foundation
var equation:NSString = "60****2" // This gives a NSInvalidArgumentException',
let expr = NSExpression(format: equation) // reason: 'Unable to parse the format string
if let result = expr.expressionValueWithObject(nil, context: nil) as? NSNumber {
let x = result.doubleValue
println(x)
} else {
println("failed")
}
Run Code Online (Sandbox Code Playgroud) 由于未捕获的异常“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 语句,但仍然在这里崩溃。有什么解决办法吗?
任何帮助,将不胜感激。