在swift中捕获无效用户输入的异常

Ché*_*éyo 11 cocoa-touch exception-handling ios nsexpression swift

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

//答案:将标题桥接到Objective-C // https://github.com/kongtomorrow/TryCatchFinally-Swift

这是同样的问题,但在objc但我想在swift中这样做.从NSExpression捕获NSInvalidArgumentException

我想要显示的只是一条消息,如果它不起作用,但现在当用户没有输入正确的格式时我得到一个例外.

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")
}
Run Code Online (Sandbox Code Playgroud)

der*_*iuk 12

更多"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
Run Code Online (Sandbox Code Playgroud)

这将生成Swift代码:

class func tryBlock((() -> Void)!) throws
Run Code Online (Sandbox Code Playgroud)

你可以用它try:

do {
    try TryCatch.tryBlock {
        let expr = NSExpression(format: "60****2")
        ...
    }
} catch {
    // Handle error here
}
Run Code Online (Sandbox Code Playgroud)


jrc*_*jrc 7

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

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

// 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
Run Code Online (Sandbox Code Playgroud)