1

I have

OBJC:

- (void)doSomething:(void (^)(NSError *))block;

SWIFT:

let test = Test()
   test.doSomething(<#T##block: ((Error?) -> Void)!##((Error?) -> Void)!##(Error?) -> Void#>)

I would rather

    try? test.doSomething { }

I would like bridging-header to translate the function into

func doSomething(block: () throws -> ()) throws {

    try block()
}

Is it possible? Thanks to all!

  • Possible duplicate of https://stackoverflow.com/questions/49324917/swift-try-inside-objective-c-block. – Martin R Mar 21 '18 at 15:25

1 Answers1

2

Your Objective-C method is declaring a parameter which is a block that receives an NSError object. It's basically declaring a callback.

If your method is not asynchronous you should declare it like this:

- (BOOL)doSomething:(NSError **)error;

Now the parameter is a pointer to an NSError* object. If the method fails for some reason, it should set an appropriate error for that parameter like so:

if (error != NULL) {
    *error = <an appropriate error>
}

Also note the BOOL return type. According to Cocoa conventions the caller should refer to the return type to determine if the method failed or not, instead of testing for the existence of an NSError* object.

Declaring a method like this will expose it in Swift using the throws mechanics.

Update:

I don't think you can declare a Swift throwing block in Objective-C. If you go the other way around, and declare your desired method signature in Swift you'll see the compiler complains it can't be represented in Objective-C.

Compiler error

Most likely the (NSError **) to throwable convention never got implemented for blocks.

pfandrade
  • 2,359
  • 15
  • 25
  • "Most likely the (NSError **) to throwable convention never got implemented for blocks" I'm exactly in this situation! Is it possible to change the signature of the ObjC method? Maybe adding some clause like NS_SWIFT_ ? – Francesco Xu Mar 22 '18 at 13:13