Is it possible that Bridging-header turns (void (^)(NSError *))block (ObjC) into block: () throws -> () (Swift)?

六月ゝ 毕业季﹏ 提交于 2021-02-10 18:21:08

问题


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!


回答1:


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.

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



来源:https://stackoverflow.com/questions/49409191/is-it-possible-that-bridging-header-turns-void-nserror-block-objc-into

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!