localizeWithFormat and variadic arguments in Swift

前端 未结 3 806
甜味超标
甜味超标 2020-12-11 23:56

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

\"My name is %@. I am %d years old\".localizeWithFormat(\"John\", 30)

w

3条回答
  •  生来不讨喜
    2020-12-12 00:24

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

提交回复
热议问题