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