小编典典

快速捕获无效用户输入的异常

swift

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

// ANSWER:将标头桥接到Objective-C //
https://github.com/kongtomorrow/TryCatchFinally-
Swift

这是相同的问题,但在objc中,但我想迅速进行

我只想显示一条消息,如果它不起作用,但是现在当用户输入的格式不正确时,我将收到一个异常消息。

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")
}

阅读 277

收藏
2020-07-07

共1个答案

小编典典

在Swift 2中,这仍然是一个问题。如上所述,最好的解决方案是使用桥接标头并在Objective C中捕获NSException。

https://medium.com/swift-programming/adding-try-catch-to-
swift-71ab27bcb5b8描述了一个很好的解决方案,但是确切的代码无法在Swift
2中编译,因为try并且catch现在是保留关键字。您需要更改方法签名以解决此问题。这是一个例子:

// 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
2020-07-07