【发布时间】:2014-09-02 19:52:50
【问题描述】:
我正在尝试这段代码,它是一个计算器。如何处理来自用户的无效输入?
//ANSWER: 将标头桥接到 Objective-C// https://github.com/kongtomorrow/TryCatchFinally-Swift
这是同样的问题,但在 objc 中,但我想快速执行此操作。 Catching NSInvalidArgumentException from NSExpression
如果它不起作用,我只想显示一条消息,但是现在当用户没有输入正确的格式时,我得到一个异常。
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")
}
【问题讨论】:
-
为什么不使用正则表达式匹配来查看可接受的方程列表。你应该考虑
automation theory来理解计算。 -
目前在 Swift 中似乎不可能捕获异常,比较 stackoverflow.com/questions/24023112/… 和链接的问题。 - 不幸的是,NSExpression(和其他 Foundation 类)没有遵循 Apple 的建议,即使用错误参数而不是抛出异常。
-
这是苹果用于 Mac 聚光灯内联计算的方法。我想知道在将字符串传递给表达式之前是否可以访问内置解析器来检查字符串。
-
我找到了这个有效的桥接文件github.com/kongtomorrow/TryCatchFinally-Swift
标签: ios cocoa-touch exception-handling swift nsexpression