在swift中捕获无效用户输入的异常 [英] Catch an exception for invalid user input in swift
问题描述
我正在尝试这是一个计算器的代码。
I am trying this code that is a calculator. How can I handle input from the user that is not valid?
// ANSWER:Bridging header to Objective-C // https://github.com/kongtomorrow/TryCatchFinally-Swift
//ANSWER: Bridging header to Objective-C// https://github.com/kongtomorrow/TryCatchFinally-Swift
这里是同样的问题,但在objc但我想在swift中这样做。 从NSExpression捕获NSInvalidArgumentException
Here is the same question but in objc but I want to do this in swift. Catching NSInvalidArgumentException from NSExpression
全部我想显示是一条消息,如果它不工作,但现在我得到一个例外,当用户没有输入正确的格式。
All I want to show is a message if it doesn't work, but now I am getting an exception when the user doesn't input the correct format.
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")
}
推荐答案
这仍然是Swift 2中的问题。如上所述,最好的解决方案是使用桥接头并捕获Objective C中的NSException。
This is still an issue in Swift 2. As noted, the best solution is to use a bridging header and catch the NSException in Objective C.
https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8 介绍了一个很好的解决方案,但确切的代码不能编译因为 try
和 catch
现在是保留关键字。您需要更改方法签名以解决此问题。下面是一个例子:
https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8 describes a good solution, but the exact code doesn't compile in Swift 2 because try
and catch
are now reserved keywords. You'll need to change the method signature to workaround this. Here's an example:
// https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8
@interface TryCatch : NSObject
+ (void)tryBlock:(void (^)())try catchBlock:(void (^)(NSException *))catch finallyBlock:(void (^)())finally;
@end
@implementation TryCatch
+ (void)tryBlock:(void (^)())try catchBlock:(void (^)(NSException *))catch finallyBlock:(void (^)())finally {
@try {
try ? try() : nil;
}
@catch (NSException *e) {
catch ? catch(e) : nil;
}
@finally {
finally ? finally() : nil;
}
}
@end
这篇关于在swift中捕获无效用户输入的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!