Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write swift 3 method with throws statement and return value that can be used in Objective C?

Below Swift 3 method is translated into Objective C like:

func doSomething(param: String) throws // Swift 3

- (BOOL)doSomething:(NSString * _Nonnull)param error:(NSError * _Nullable * _Nullable)error; // Translated Objective C

Then, how can I write a method with both throws and a return type?

func doSomething(param: String) throws -> Int // Swift 3

// Error: Never translated into Objective C

I know flow should not be handled by NSError object. It just contains information about an error. And that's why there's a BOOL return type to let us know the invocation is succeeded without any problem.

Then how can I handle a method with both throws statement and return type? Is there a standard way to handle this?

Thank you in advance.

like image 489
ccoroom Avatar asked Mar 03 '17 04:03

ccoroom


1 Answers

The standard way of reporting success or failure in Objective-C is to return the boolean value NO or a nil object pointer, as documented in Using and Creating Error Objects:

Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

So you can return a instance of an object

func doSomething(param: String) throws -> NSNumber

which is translated to

- (NSNumber * _Nullable)doSomethingWithParam:(NSString * _Nonnull)param error:(NSError * _Nullable * _Nullable)error;

and returns nil if an error is thrown, or return a boolean and pass other values back by reference

func doSomething(param: String, value: UnsafeMutablePointer<Int>) throws

which is mapped to

- (BOOL)doSomethingWithParam:(NSString * _Nonnull)param value:(NSInteger * _Nonnull)value error:(NSError * _Nullable * _Nullable)error;
like image 112
Martin R Avatar answered Oct 18 '22 23:10

Martin R