OGeek|极客世界-中国程序员成长平台

标题: ios - 在 Swift 中使用 Objective-C block 时保留参数类型 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:07
标题: ios - 在 Swift 中使用 Objective-C block 时保留参数类型

我刚刚开始在 Swift 而不是 Objective-c 中实现我们的一些新功能,到目前为止一切正常,但让我感到困惑的一件事是如何在 Swift 中正确使用 Obj-C block 。

在我的 Obj-C 类中,我定义了一个 block ,用于处理对我们 API 的调用的 HTTP 响应:

typedef void(^CCAPIClientRequestCompletionBlock)(id response, NSArray *messages, NSDictionary *metaData, NSError *error);

这用于以下方法:

-(void)createMeetingWithUsersNSArray *)users subjectNSString *)subject andDescriptionNSString *)description withCompletionBlockCCAPIClientRequestCompletionBlock)completionBlock;

我现在正在编写一个 API 客户端来访问我们在 Swift 中的 API 的一个新领域,并尝试将 block 重用为闭包。下面的代码构建并运行:

apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response, messages, metaData, error) -> Void in

    }

但我希望能够保留参数类型,并认为我应该能够执行以下操作:

apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response:Any?, messages:[Any], metaData:[AnyHashable:Any], error:NSError) -> Void in

    }

但是当我尝试这个时,我得到一个错误:

Cannot convert value of type '(Any?, [Any], [AnyHashable : Any], NSError) -> Void' to expected argument type 'CCAPIClientRequestCompletionBlock!'

我在这里错过了什么?



Best Answer-推荐答案


您应该将所有类型更改为可选项并将 NSError 更改为 Error?:

apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response:Any?, messages:[Any]?, metaData:[AnyHashable:Any]?, error:Error?) -> Void in 
   //TODO 
}

关于ios - 在 Swift 中使用 Objective-C block 时保留参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510557/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4