gpt4 book ai didi

ios - 在 Objective-C 中处理闭包中的快速抛出

转载 作者:行者123 更新时间:2023-11-30 12:33:58 29 4
gpt4 key购买 nike

我有一个 Objective-C 函数,如下所示


+ (void) invokeSortingWithClassName: (NSString*) 类名函数名: (NSString*) 函数名闭包: (id(^)(NSArray* arr))closure;

我必须从 swift 类中调用这个方法。调用此方法的 swift 代码如下所示

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

在闭包定义开始时,我收到此附加错误 enter image description here

本质上,这个闭包会抛出一个错误,我不确定如何在这个函数的 Objective-C 定义中处理这个错误。请帮我解决这个错误

最佳答案

虽然可以使用 throws 声明闭包,但该闭包尚未使用 throws 声明,因此您的闭包无法抛出 - 这正是错误消息所告诉的内容你。

由于该函数是在 Objective-C 中声明的,因此无法更改函数签名以包含 throws,因为 Objective-C 对 Swift 异常一无所知。

在 Swift 和 Objective-C 之间转换错误处理的标准方式是让 Objective-C block 接收 &NSError 参数。

如果您有能力更改 Objective-C 方法签名,则应将其声明为

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

这将允许您从 swift 中抛出,并通过 Objctive-C 中的 error 参数接收到错误。

如果您无法更改方法签名,则需要在闭包中捕获异常并简单地返回一个“错误”值,例如nil

关于ios - 在 Objective-C 中处理闭包中的快速抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43110101/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com