Pass a quick close to objective-C function, which takes a block as a parameter

I have a function in objective-C as shown below

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

I want to pass a quick callback closure like this:

fetchChannelListForWatch(replyHandler)

where responseHandler is a type closure

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

and I get the error:

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

Handler comes from WatchConnectivity delegate

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

therefore, I cannot change the type of responseHandler.

How to skip my quick close with option

replyHandler: [String: AnyObject] -> () 

to objective-C function, which takes a block with parameter

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

Your help is much appreciated!

+4
source share
2 answers

I think this may be a shortcut for 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]?)
        }
}
+2
source

The bridge type for NSDictionary is

[NSObject: AnyObject]

In your case, you need to upgrade replyHandlerto

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

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

+2

All Articles