Catch an exception for invalid user input in swift

前端 未结 3 1269
悲哀的现实
悲哀的现实 2020-11-28 16:02

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/kon

3条回答
  •  悲&欢浪女
    2020-11-28 16:20

    More "Swifty" solution:

    @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
    

    This will generate Swift code:

    class func tryBlock((() -> Void)!) throws
    

    And you can use it with try:

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

提交回复
热议问题