11

How should I invoke the following method? The method belongs to a class that prints logs.

func log(format: String!, withParameters valist: CVaListPointer)

What I want to achieve, would look like this in Objective-C:

NSLog(@"Message %@ - %@", param1, param2);

Any ideas?

mikywan
  • 1,495
  • 1
  • 19
  • 38

1 Answers1

24

CVaListPointer is the Swift equivalent of the C va_list type and can be created from an [CVarArgType] array using withVaList().

Example:

func log(format: String!, withParameters valist: CVaListPointer) {
    NSLogv(format, valist)
}

let args: [CVarArgType] = [ "foo", 12, 34.56 ] 
withVaList(args) { log("%@ %ld %f", withParameters: $0) }

Output:

2016-04-27 21:02:54.364 prog[6125:2476685] foo 12 34.560000

For Swift 3, replace CVarArgType by CVarArg.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    What can you recommend for a function that takes `CVarArg` instead of `CVaListPointer`? – kelin Feb 06 '17 at 23:55
  • If replace `CVarArgType` by `CVarArg`, compiler will show an error because of type, and if you try to cast `CVarArg` to `CVarArgType`, you will get a crash. – kelin Feb 07 '17 at 00:40
  • There is `getVaList()` method also which return `CVaListPointer` given a list of `CVarArg`. – Ahmed Osama Oct 18 '20 at 19:37
  • @AhmedOsama: According to https://developer.apple.com/documentation/swift/1539624-getvalist, `withVaList` is the preferred method. – Martin R Oct 18 '20 at 19:40