3

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")
Pang
  • 9,564
  • 146
  • 81
  • 122
  • Possible duplicate of [How do you call an Objective-C variadic method from Swift?](http://stackoverflow.com/questions/24195796/how-do-you-call-an-objective-c-variadic-method-from-swift). – Summary: You *cannot* call a function with a variable argument list from Swift, only functions taking a `va_list` parameter. – Martin R Jun 18 '15 at 16:48

2 Answers2

3

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.

Community
  • 1
  • 1
-1
  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

iAnurag
  • 9,286
  • 3
  • 31
  • 48