桥接标题是否有可能将(void(^)(NSError *))块(ObjC)变成块:()抛出->.()(迅速)? [英] Is it possible that Bridging-header turns (void (^)(NSError *))block (ObjC) into block: () throws -> () (Swift)?

查看:43
本文介绍了桥接标题是否有可能将(void(^)(NSError *))块(ObjC)变成块:()抛出->.()(迅速)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

OBJC:

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

SWIFT:

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

我宁愿

    try? test.doSomething { }

我希望桥接头将函数转换为

I would like bridging-header to translate the function into

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

    try block()
}

有可能吗?谢谢大家!

推荐答案

您的Objective-C方法正在声明一个参数,该参数是一个接收NSError对象的块.基本上是在声明回调.

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;

现在参数是一个指向NSError *对象的指针.如果该方法由于某种原因而失败,则应为该参数设置一个适当的错误,如下所示:

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>
}

还要注意BOOL返回类型.根据Cocoa约定,调用者应参考返回类型来确定方法是否失败,而不是测试是否存在NSError *对象.

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.

声明这样的方法将使用 throws 机制在Swift中公开它.

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

更新:

我认为您无法在Objective-C中声明Swift抛出块.如果您反其道而行之,并在Swift中声明所需的方法签名,则会看到编译器抱怨它无法在Objective-C中表示.

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.

(NSError **)易引发的约定很可能从未针对块实现.

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

这篇关于桥接标题是否有可能将(void(^)(NSError *))块(ObjC)变成块:()抛出->.()(迅速)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆