简体   繁体   中英

call function in swift file from objective-c file with completion handler (closure) syntax

I am having trouble calling a function in a swift file from an objective-c file where there is a closure in the swift function.

This is the Swift function

//In Utilities class

static func getString(query: NSString, completion: @escaping (_ response: NSString) -> Void) {

        completion("hello")
    }

This is how I try to call it in the objective-c class:

 [Utilities getString:@"hi there" completion:^(NSString* response) {
     NSLog(response);
    }];

I'm getting the error 'No known class method for selector 'getString:completion:'

What is wrong with above?

Note: I am able to call a simpler method without the closure/completion bloc.

in swift class
static func myTest () {
      print("function called")
    }

called from objective-c class with:

[Utilities myTest];

SO the problem seems to relate to the closure syntax.

Surround the class with

@objcMembers class Utilities:NSObject {

or the function

@objc class func getString(query: NSString, completion: @escaping (_ response: NSString) -> Void) {

[Utilities getStringWithQuery:@"hi there" completion:^(NSString* response) {
 NSLog(response);
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM