4

I am trying to create a String extension to do something like that

"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 give me the following compilation error

Type CVaListPointer does not conform to protocol CVargType

Anyone knows how to work aroundthis compilation error?

Pierre
  • 686
  • 8
  • 19

3 Answers3

5

This should be pretty simple just change your parameters as follow:

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)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Oups sorry, maybe it wasnt clear in the question, but my goal was to create something generic, using variadic arguments – Pierre Jan 13 '15 at 06:06
  • Thks Leonardo, this compile but it would not let me translate a a localized string with argument since you are not using String.localizedStringWithFormat – Pierre Jan 13 '15 at 16:37
1

This allows localized string with variadic 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")
Ciryon
  • 2,637
  • 3
  • 31
  • 33
-3

In Swift 3

func localize(key: String, arguments: CVarArg...) -> String {
  return String(format: NSLocalizedString(key, comment: ""), arguments)
}
onmyway133
  • 45,645
  • 31
  • 257
  • 263