LocalizeWithFormat and variable arguments in Swift
I am trying to create a string extension to do something like this
"My name is %@. I am %d years old".localizeWithFormat("John", 30)
which looks like this
extension String {
func localizeWithFormat(arguments: CVarArgType...) -> String {
return String.localizedStringWithFormat(
NSLocalizedString(self,
comment: ""), getVaList(arguments))
}
}
it gives me the following compilation error
CVaListPointer type does not match CVargType protocol
Does anyone know how to deal with this compilation error?
+3
source to share
3 answers
It should be fairly simple to change the parameters like this:
extension String {
func localizeWithFormat(name:String,age:Int, comment:String = "") -> String {
return String.localizedStringWithFormat( NSLocalizedString(self, comment: comment), name, age)
}
}
"My name is %@. I am %d years old".localizeWithFormat("John", age: 30) // "My name is John. I am 30 years old"
init (format: locale: arguments :)
extension String {
func localizeWithFormat(args: CVarArgType...) -> String {
return String(format: self, locale: nil, arguments: args)
}
func localizeWithFormat(local:NSLocale?, args: CVarArgType...) -> String {
return String(format: self, locale: local, arguments: args)
}
}
let myTest1 = "My name is %@. I am %d years old".localizeWithFormat(NSLocale.currentLocale(), args: "John",30)
let myTest2 = "My name is %@. I am %d years old".localizeWithFormat("John",30)
+4
source to share
This allows you to use a localized string with variable arguments:
extension String {
func localizedStringWithVariables(vars: CVarArgType...) -> String {
return String(format: NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: ""), arguments: vars)
}
}
Call using:
"Hello, %@. Your surname is: %@.".localizedStringWithVariables("Neil", "Peart")
+1
source to share