Search code examples
iosobjective-cswiftnsdictionaryswift-dictionary

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!


Solution

  • 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]?)
            }
    }