快速捕获无效用户输入的异常 [英] Catch an exception for invalid user input in swift

查看:27
本文介绍了快速捕获无效用户输入的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying this code that is a calculator. How can I handle input from the user that is not valid?

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

//ANSWER: Bridging header to Objective-C// https://github.com/kongtomorrow/TryCatchFinally-Swift

这是同样的问题,但在 objc 中,但我想快速完成.从 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 描述了一个很好的解决方案,但确切的代码不能在 Swift 2 中编译,因为 trycatch 现在是保留关键字.您需要更改方法签名来解决此问题.举个例子:

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

这篇关于快速捕获无效用户输入的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆