I have below code in swift 3:
class StringUtility {
static func Localizer(tableName: String?) -> (_ key: String, _ params: CVarArg...) -> String {
return { (key: String, params: CVarArg...) in
let content = NSLocalizedString(key, tableName: tableName, comment: "")
if params.isEmpty {
return content
}
print(params) ->>>>>> this prints [[[Wells Fargo]]]
return NSString.init((format: content, arguments: getVaList(params))) as String
}
}
}
func localizationHelper(tableName: String, key: String, params: CVarArg...) -> String {
let t = StringResourceUtility.Localizer(tableName: tableName)
print(params) - >>>>>>>>>> this prints [[Wells Fargo]]
return t(key, params)
}
If you see the print statements in above two functions, [] are appended every time CVarArg is passed inside functions resulting in wrong localization string outputted.
1) CVarArg cannot be passed multiple times like in above code ? 2) how to fix this ?
You cannot pass a variable argument list to another function, you
have to pass a CVaListPointer
instead. Also withVaList
should
be used instead of getVaList
:
class StringResourceUtility {
static func Localizer(tableName: String?) -> (_ key: String, _ params: CVaListPointer) -> String {
return { (key: String, params: CVaListPointer) in
let content = NSLocalizedString(key, tableName: tableName, comment: "")
return NSString(format: content, arguments: params) as String
}
}
}
func localizationHelper(tableName: String, key: String, params: CVarArg...) -> String {
let t = StringResourceUtility.Localizer(tableName: tableName)
return withVaList(params) { t(key, $0) }
}
Example:
let s = localizationHelper(tableName: "table", key: "%@ %@", params: "Wells", "Fargo")
print(s) // Wells Fargo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With