简体   繁体   中英

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

I have a function in objective-C as following

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

I want to pass a swift callback closure into this like this:

fetchChannelListForWatch(replyHandler)

where replyHandler is a closure of type

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

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

so I cannot change the type of replyHandler.

How can I pass my swift closure with parameter

replyHandler: [String: AnyObject] -> () 

into an objective-C function that takes a block with parameter

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

Your help is much appreciated!

The bridged type for NSDictionary is

[NSObject: AnyObject]

In your case you need to update your replyHandler to

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

Here is the relevant documentation 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]?)
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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