Search code examples
iosobjective-cswiftfunctionreturn

Return function from a function in Objective C?


I am using this swift function inside my objective c project to parse a JSON, this function looks like this: (This function is inside NetworkService class)

static func parseJSONString(jsonString: String?, key: String?) -> () -> String{
    var jsonSubString = String()
    func parseString() -> String{
        if let data = jsonString?.data(using: .utf8){
            if let content = try? JSONSerialization.jsonObject(with: data, options: []),
                let array = content as? [[String: AnyObject]]
            {

                for jsondict in array {
                    jsonSubString = jsondict[key!] as! String
                }
            }
        }
        return jsonSubString
    }
    return parseString
}

I want to call this function inside ViewController which is Objective C. It is a static method. Please help me in calling this function.


Solution

  • You have to expose the function to Objective-C.

    If your class is not already exposed to Objective-C you have to mark it with the @objc directive and inherit from NSObject, like this:

    @objc class NetworkService: NSObject {
    
        static func parseJSONString(jsonString: String?, key: String?) -> () -> String{
            var jsonSubString = String()
            func parseString() -> String{
                if let data = jsonString?.data(using: .utf8){
                    if let content = try? JSONSerialization.jsonObject(with: data, options: []),
                        let array = content as? [[String: AnyObject]]
                    {
    
                        for jsondict in array {
                            jsonSubString = jsondict[key!] as! String
                        }
                    }
                }
                return jsonSubString
            }
            return parseString
        }
    }
    

    Then in Objective-C you include the swift-generated header (I recommend including it in the .m-file), which is usually named [your-product-name-here]-Swift.h

    You now should be able to call your function from Objective-C like this:

    NSString* (^parseJson)(void) = [NetworkService parseJSONStringWithJsonString:@"SomeString" key:@"SomeOtherString"];
    NSString* result = parseJson();
    

    or simply like this:

    NSString* otherResult = [NetworkService parseJSONStringWithJsonString:@"SomeString"
                                                                      key:@"SomeOtherString"]();
    

    More on this in documentation from Apple here