I think that everybody knows how the error handling works when you call Objective-C methods from Swift. If you accidentally missed it, here’s quote from the Using Swift with Cocoa and Objective-C book:

In Cocoa, methods that produce errors take an NSError pointer parameter as their last parameter, which populates its argument with an NSError object if an error occurs. Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift’s native error handling functionality.

Read this book to learn more. I’m going to focus on one corner case only.

Let’s say I have following method in Objective-C:

- (User *)findUserWithObjectId:(NSString *)objectId
error:(NSError **)error;

Translated method signature in Swift:

func findUserWithObjectId(objectId: String) throws -> User

As you can see, Swift method:

  • return value type is not optional User?, but just User,
  • error is thrown if Objective-C method isn’t able to find user and returns nil.

But what happens if Objective-C method returns nil and the output error is not set? Error is thrown anyway. Swift creates _SwiftNativeNSError with domain set to Foundation._GenericObjCError and code to 0, NilError. If you see this error, don’t panic, just check your Objective-C implementation or ask Framework provider to fix it.

Closely related case is an Objective-C method, which does return some value and also sets the output error as well. There’s no way how to get this error in Swift. If your framework is written in Objective-C, your goal is to provide good interoperability with Swift as well, don’t do this. Swift isn’t going to call catch block, because return value does not equal to nil.