简体   繁体   English

在Objective-C中处理快速关闭

[英]Handle swift throw in closure in objective-c

I've an objective-c function that looks like below 我有一个目标C函数,如下所示

+ (void) invokeSortingWithClassName: (NSString*) className functionName: (NSString*) functionName closure: (id(^)(NSArray* arr))closure;

and I've to call this method from a swift class. 我必须从一个快速的类中调用此方法。 The swift code that calls this method looks like below 调用此方法的快速代码如下所示

SortHandler.invokeSorting(withClassName: className, functionName: functionName, closure:
{
    args in 
    let something = unwrap(args!)
    do
    {
        let returnValue = try closure(something as NSArray!) //this is another closure coming as a parameter in the function in which this code is written and this throws
        return returnValue;
    }
    catch
    {
        throw error

    }
    return "-1" as! T
})

At the start of closure definition, I get this attached error 在闭包定义开始时,出现此错误 在此处输入图片说明

Essentially, this closure throws an error and I am not sure, how to handle this error in objective-c definition of this function. 本质上,此闭包引发一个错误,我不确定如何在此函数的Objective-C定义中处理该错误。 Please help me fix this error 请帮助我解决此错误

While a closure can be declared with throws , this closure has not been declared with throws , so your closure cannot throw - this is exactly what the error message is telling you. 尽管可以使用throws声明闭包,但是尚未使用throws声明此闭包,因此您的闭包不能抛出-这正是错误消息告诉您的内容。

Since the function is declared in Objective-C, the function signature can't be changed to include throws as Objective-C doesn't know anything about Swift exceptions. 由于函数是在Objective-C中声明的,因此函数签名不能更改为包含throws因为Objective-C对Swift异常一无所知。

The standard way in which error handling is translated between Swift and Objective-C is for the Objective-C block to receive an &NSError parameter. 在Swift和Objective-C之间转换错误处理的标准方法是让Objective-C块接收&NSError参数。

If you have the ability to change the Objective-C method signature, it should be declared as 如果您有能力更改Objective-C方法签名,则应将其声明为

+(void) invokeSortingWithClassName: (NSString* _Nullable) className functionName: (NSString* _Nullable) functionName closure: (id _Nullable (^_Nullable)(NSArray* _Nullable arr, NSError* _Nullable * _Nullable error))closure;

This will allow you to throw from swift with the error being received via the error parameter in Objctive-C. 这将允许你throw通过该接收的错误迅速从error中Objctive-C参数。

If you cannot change the method signature, then you will need to catch the exception in your closure and simply return an 'error' value, such as nil 如果您无法更改方法签名,则需要在闭包中捕获异常并仅返回“错误”值,例如nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM