How to format localised strings in Swift?

You can use %@ in Swift's String(format:...), it can be substituted by a Swift String or any instance of a NSObject subclass. For example, if the Localizable.strings file contains the definition

"From %@, %@" = "从 %@, %@ 得出";

then

let x = 1.2
let y = 2.4
let text = String(format: NSLocalizedString("From %@, %@", comment: ""), "\(x)", "\(y)")
// Or alternatively:
let text = String(format: NSLocalizedString("From %@, %@", comment: ""), NSNumber(double: x), NSNumber(double: y))

produces "从 1.2, 2.4 得出". Another option would be to use the %f format for double floating point numbers:

"From %f, %f" = "从 %f, %f 得出";

with

let text = String(format: NSLocalizedString("From %f, %f", comment: ""), x, y)

See Niklas' answer for an even better solution which localizes the number representation as well.


From WWDC 2017:

let format = NSLocalizedString("%d popular languages", comment:"Number of popular languages")
label.text = String.localizedStringWithFormat(format, popularLanguages.count)

One more simple example

let changeable = "something"
let result = String(format: NSLocalizedString("stringId", comment: ""), arguments: [changeable]) // Hello World and something

localizable.strings with

"stringId" = "Hello World and %@";
  • comment parameter doesn't have effect on result and is used for translators and by genstrings code-gen as comment