How call a function objective c with args in swift

2.3k views Asked by At

I have the next function in objective 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 such that when I call the function can be:

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

Note that the second param not have alias how this.

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

There are 2 answers

0
Noe Miranda Franco On BEST ANSWER

I solved follow:

in objective 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 swift app delegate 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 based in the post duplicated How do you call an Objective-C variadic method from Swift?

thanks.

1
iAnurag On
  1. Simply import your class containing this method in YourProjectname-Bridging-Header.h file.

     #import "`YourClass.h"
    
  2. Create imported class's object

     var a = YourClass()
    
  3. then simply call the method and pass required parameter

    a.getNsLog(yourParameters)
    

I hope this helps