Force Objective-C method returning `id` and inout NSError to bridge to an optional return

452 Views Asked by At

Consider this Objective-C class:

@interface TestAPI : NSObject

-(nullable id)aNullableMethod;

-(nullable id)aNullableMethodWithError:(inout NSError **)error;

@end

I'm using TestAPI as an abstract base class and want to inherit from it in Swift.

Swift bridges this code to look like this (i.e. Counterparts menu -> Swift 4.2 Interface):

open class TestAPI : NSObject {

    open func aNullableMethod() -> Any?

    open func aNullableMethodWithError() throws -> Any
}

The problem is that aNullableMethodWithError() can return nil as a valid value.

How do I convince Swift that aNullableMethodWithError() returns Any? and not Any?

Or is there a better way to write the Objective-C method signature?

1

There are 1 best solutions below

0
OOPer On

You may need to use NS_SWIFT_NOTHROW:

-(nullable id)aNullableMethodWithError:(inout NSError **)error NS_SWIFT_NOTHROW;

This is imported into Swift as:

open func aNullableMethodWithError(_ error: NSErrorPointer) -> Any?

If you want to import your method as throws-function, you may need to change the method signature to follow the convention:

  • Return true or non-nil on no error
  • Return false or nil on error

Something like this:

-(BOOL)aNullableMethod:(id*)object withError:(inout NSError **)error;

In Swift:

open func aNullableMethod(_ object: AutoreleasingUnsafeMutablePointer<AnyObject?>!) throws