How to call function c function using args in swift

I have the following function in object c

+ (NSString *)getNsLog:(NSString *)pString, ...{
    va_list args;
    va_start(args, pString);
    NSLogv(pString, args);
    va_end(args);

    return [[NSString alloc] initWithFormat:pString arguments:args]; 
}

      

how can i call this function from swift or convert the code to swift so that when calling the function one can:

getNslog("my value1 =  %@ value2 = %@","hello","world")

      

Note that the second parameter is not aliased like this.

getNslog("my value1 =  %@ value2 = %@", args:"hello","world")

      

+3


source to share


2 answers


I solved the following:

in object c change my code to this:

+(NSString*)getNsLog:(NSString*)pString args:(va_list)args{

NSLogv(pString, args);

va_end(args);

return [[NSString alloc] initWithFormat:pString arguments:args];
}

      

in the quick release of the application I add

extension MyClass {
class func getNsLog(format: String, _ args: CVarArgType...) -> NSString?
    {
    return MyClass.getNsLog(format, args:getVaList(args))
    }
}

      



now i can call the function

NSLog("%@", MyClass.getNsLog("%@,%@", "hello","World")!)

      

I was based on post duplicated What do you call Objective-C variational method from Swift?

thank.

+3


source


  • Just import the class containing this method into a file YourProjectname-Bridging-Header.h

    .

     #import "`YourClass.h"
    
          

  • Create object of imported class

     var a = YourClass()
    
          

  • then just call the method and pass the required parameter

    a.getNsLog(yourParameters)
    
          



I hope this helps

-1


source







All Articles