Catch an exception for invalid user input in swift

前端 未结 3 1271
悲哀的现实
悲哀的现实 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:15

    A nice solution editing from https://github.com/kongtomorrow/TryCatchFinally-Swift:

    First create TryCatch.h & TryCatch.m and bridge them to Swift:

    TryCatch.h

    #import 
    
    void tryCatch(void(^tryBlock)(), void(^catchBlock)(NSException *e), void(^finallyBlock)());
    

    TryCatch.m

    #import 
    
    void tryCatch(void(^tryBlock)(), void(^catchBlock)(NSException *e), void(^finallyBlock)()) {
        @try {
            tryBlock();
        }
        @catch (NSException *exception) {
            catchBlock(exception);
        }
        @finally {
            finallyBlock();
        }
    }
    

    Then create the class TryCatch in Swift:

    func `try`(`try`:()->()) -> TryCatch {
        return TryCatch(`try`)
    }
    class TryCatch {
        let tryFunc : ()->()
        var catchFunc = { (e:NSException!)->() in return }
        var finallyFunc : ()->() = {}
    
        init(_ `try`:()->()) {
            tryFunc = `try`
        }
    
        func `catch`(`catch`:(NSException)->()) -> TryCatch {
            // objc bridging needs NSException!, not NSException as we'd like to expose to clients.
            catchFunc = { (e:NSException!) in `catch`(e) }
            return self
        }
    
        func finally(finally:()->()) {
            finallyFunc = finally
        }
    
        deinit {
            tryCatch(tryFunc, catchFunc, finallyFunc)
        }
    }
    

    Finally, use it! :)

    `try` {
        let expn = NSExpression(format: "60****2")
    
        //let resultFloat = expn.expressionValueWithObject(nil, context: nil).floatValue
        // Other things...
        }.`catch` { e in
            // Handle error here...
            print("Error: \(e)")
    }
    

提交回复
热议问题