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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)