4

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!

Jacky Wang
  • 618
  • 7
  • 27

2 Answers2

2

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

Ben Trengrove
  • 8,191
  • 3
  • 40
  • 58
  • Hey @Ben, thanks for the information. But in my case, the replyHandler is part of a delegate callback. specifically the didReceiveMessage function from WatchConnectivity. So I can't change the type of my replyHandler, casting it to ([NSObject : AnyObject]) -> Void) doesn't work either. Would you know how to get around this? Thanks! – Jacky Wang Jun 24 '15 at 10:46
2

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]?)
        }
}
agy
  • 2,804
  • 2
  • 15
  • 22