【问题标题】:Retaining parameter types when using Objective-C block in Swift在 Swift 中使用 Objective-C 块时保留参数类型
【发布时间】:2017-02-28 13:51:43
【问题描述】:

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

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

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

这用于以下方法:

-(void)createMeetingWithUsers:(NSArray *)users subject:(NSString *)subject andDescription:(NSString *)description withCompletionBlock:(CCAPIClientRequestCompletionBlock)completionBlock;

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

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!'

我在这里错过了什么?

【问题讨论】:

  • 您没有声明任何可空性属性,但不知何故您希望响应是可选的。这怎么可能?

标签: ios objective-c swift closures


【解决方案1】:

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

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

【讨论】:

  • Swift 已经将它们视为未包装的选项。尝试使它们明确,例如apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response:Any?, messages:[Any]!, metaData:[AnyHashable:Any]!, error:NSError!) -> Void in }
  • 做到了!谢谢。
  • 等等……不。那是引导我前进的编译器。它仍然错误。
  • @darkbreed it still errors 是什么意思?还是一样的错误吗?
  • 是的,对不起 - 同样的错误。它似乎并不关心它们是可选的还是显式的。无论如何,我都会收到 Cannot convert value of type '(Any?, [Any], [AnyHashable : Any], NSError) -> Void' to expected argument type 'CCAPIClientRequestCompletionBlock!' 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 2019-03-08
  • 2023-01-12
  • 2021-09-26
  • 1970-01-01
  • 2017-12-15
相关资源
最近更新 更多