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

3.7k views Asked by At

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!

2

There are 2 answers

0
agy On BEST ANSWER

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]?)
        }
}
1
Ben Trengrove On

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