相关疑难解决方法(0)

在swift中捕获无效用户输入的异常

我正在尝试这个计算器代码.如何处理无效的用户输入?

//答案:将标题桥接到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)

cocoa-touch exception-handling ios nsexpression swift

11
推荐指数
2
解决办法
3039
查看次数

检查表达式是否有效

由于未捕获的异常“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 语句,但仍然在这里崩溃。有什么解决办法吗?

任何帮助,将不胜感激。

math try-catch nsexpression swift4

1
推荐指数
1
解决办法
1320
查看次数