Adding Try-Catch to Swift

William Falcon
Swift Programming
Published in
3 min readOct 10, 2014

--

I’m addicted to Swift. As a legacy Objective-C developer, I’ve had a blast over the last few months using Swift. However, I’ve found the lack of try/catch a little infuriating.

I’ll walk you through implementing your own try-catch for Swift. If you need it fast, download the code here.

Strategy

We’re going to build a wrapper around the traditional Objective-c try-catch and pass in Swift closures to execute as part of the code.

Steps:

  • Create a new Objective-c class. Pick NSObject as the subclass.
  • Allow Xcode to add a bridging header if you don’t already have one. The bridging header allows Swift code to access Objective-c classes imported through there.
  • Make your TryCatch class visible to the Swift project by importing the Objective-c header.
  • Declare your new try-catch function. We’re using a + to make it a class function for easy use.
+ (void)try:void(^)())try catch:void(^)(NSException*exception))catch finally:void(^)())finally;
  • Implement the function using the default Objective-c try-catch.
  • Call the closures (blocks) inside each matching part of the try-catch. Only call if the closure (block) isn’t nil.
+(void)try:void (^)())try catch:void (^)(NSException *))catch finally:void (^)())finally{    @try {       try ? try() : nil;    }    @catch (NSException *exception) {       catch ? catch(exception) : nil;    }    @finally {       finally ? finally() : nil;    }}

Usage

Use anywhere you need a try catch in your Swift project.

 TryCatch.try({ () -> Void in    //try stuff }, catch: { (exception) -> Void in    //catch exceptions }) { () -> Void in    //close resources }

Harlem App Collective is a design focused, mobile development shop based in Harlem, NY. Email: hi@hacstudios.com

--

--

William Falcon
Swift Programming

⚡️PyTorch Lightning Creator • PhD Student, AI (NYU, Facebook AI research).