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")