简体   繁体   English

将swift闭包传递给objective-C函数,该函数将块作为参数

[英]Pass a swift closure to an objective-C function which takes a block as parameter

I have a function in objective-C as following 我在Objective-C中有一个函数如下

- (void) fetchChannelListForWatch:(void (^)(NSDictionary *))callback

I want to pass a swift callback closure into this like this: 我想将swift回调闭包传递给这样:

fetchChannelListForWatch(replyHandler)

where replyHandler is a closure of type 其中replyHandler是一个类型的闭包

replyHandler: ([String : AnyObject]) -> Void)

and I get the error: 我收到错误:

Cannot invoke 'fetchChannelListForWatch' with an argument list of type '(([String : AnyObject]) -> Void)'

The replyHandler is coming from WatchConnectivity delegate replyHandler来自WatchConnectivity委托

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)

so I cannot change the type of replyHandler. 所以我无法改变replyHandler的类型。

How can I pass my swift closure with parameter 如何通过参数传递我的快速闭包

replyHandler: [String: AnyObject] -> () 

into an objective-C function that takes a block with parameter 进入一个带有参数块的objective-C函数

- (void) fetchChannelListForWatch:(void (^)(NSDictionary *))callback

Your help is much appreciated! 非常感谢您的帮助!

The bridged type for NSDictionary is NSDictionary的桥接类型是

[NSObject: AnyObject]

In your case you need to update your replyHandler to 在您的情况下,您需要将replyHandler更新为

replyHandler: ([NSObject : AnyObject]) -> Void)

Here is the relevant documentation https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html 以下是相关文档https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

I think this could be a shortcut to your problem: 我认为这可能是您问题的捷径:

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void){
      let objCObject = ObjectiveCClass()

      objCObject.fetchChannelListForWatch { (dict) -> Void in
            replyHandler(dict as! [String : AnyObject]?)
        }
}

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

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