Swift function with args... pass to another function with args
Similar as in (Objective-)C, you cannot pass a variable argument list
directly to another function. You have to create a CVaListPointer
(the Swift equivalent of va_list
in C) and call a function which
takes a CVaListPointer
parameter.
So this could be what you are looking for:
extension String {
func getLocalizeWithParams(args : CVarArgType...) -> String {
return withVaList(args) {
NSString(format: self, locale: NSLocale.currentLocale(), arguments: $0)
} as String
}
}
withVaList()
creates a CVaListPointer
from the given argument list
and calls the closure with this pointer as argument.
Example (from the NSString
documentation):
let msg = "%@: %f\n".getLocalizeWithParams("Cost", 1234.56)
print(msg)
Output for US locale:
Cost: 1,234.560000
Output for German locale:
Cost: 1.234,560000
Update: As of Swift 3/4/5 one can pass the arguments to
String(format: String, locale: Locale?, arguments: [CVarArg])
directly:
extension String {
func getLocalizeWithParams(_ args : CVarArg...) -> String {
return String(format: self, locale: .current, arguments: args)
}
}