1

I have the following code:

public static func e(file: String = __FILE__,
    function: String = __FUNCTION__,
    line: Int = __LINE__,format: String, args: CVarArgType...)
{
    NSLog([%d]\t [%@] " + format,line,function, args); //<<< I have no idea how to pass the params here
}

I get compiler error on NSLog that can not be called as I did.

Simply I need to print the var args, function name and line using a single NSLOG call.

Colateral
  • 1,736
  • 2
  • 18
  • 22

1 Answers1

4

Similar as in Swift function with args... pass to another function with args, you have to create a CVaListPointer (the Swift equivalent of va_list in C) and call a function which takes a CVaListPointer parameter, in this case NSLogv().

public class Logger {
    public static func e(
        format: String,
        file: String = __FILE__,
        function: String = __FUNCTION__,
        line: Int = __LINE__,
        args: CVarArgType...)
    {
        let extendedFormat = "[%d]\t [%@] " + format
        let extendedArgs : [CVarArgType] = [ line, function ] + args
        withVaList(extendedArgs) { NSLogv(extendedFormat, $0) }
    }
}

// Example usage:
Logger.e("x = %d, y = %f, z = %@", args: 13, 1.23, "foo")

I have made format the first parameter, so that is has no external parameter name. The variable argument list must be the last parameter in Swift 1.2, and the external parameter cannot be avoided in this combination with default parameters.

In Swift 2 you can avoid the external parameter name for the variable arguments:

public class Logger {
    public static func e(
        format: String,
        _ args: CVarArgType...,
        file: String = __FILE__,
        function: String = __FUNCTION__,
        line: Int = __LINE__)
    {
        let extendedFormat = "[%d]\t [%@] " + format
        let extendedArgs : [CVarArgType] = [ line, function ] + args
        withVaList(extendedArgs) { NSLogv(extendedFormat, $0) }
    }
}

// Example usage:
Logger.e("x = %d, y = %f, z = %@", 13, 1.23, "foo")
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382