我正在尝试这段代码,它是一个计算器。如何处理来自用户的无效输入?
//答案:桥接 header 到 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")
}
最佳答案
更多“Swifty”解决方案:
@implementation TryCatch
+ (BOOL)tryBlock:(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
这将生成 Swift 代码:
class func tryBlock((() -> Void)!) throws
您可以将它与 try
一起使用:
do {
try TryCatch.tryBlock {
let expr = NSExpression(format: "60****2")
...
}
} catch {
// Handle error here
}
关于ios - 在 swift 中捕获无效用户输入的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24710424/