How do I format localized strings in Swift?
I am learning to localize my application in Simplified Chinese. I am following this tutorial on how to do this.
Since the tutorial is based on Obj-C, the formatted strings can be written like this:
"Yesterday you sold %@ apps" = "Ayer le vendió %@ aplicaciones";
"You like?" = "~ Es bueno? ~";
But I am using Swift. And in Swift I don't think you can use %@
to indicate that there is something in there. Do we have correct string interpolation?
My application is related to mathematics. And I want to show what input is used to calculate the result in the detailed cell label of the table view. for example
--------------
1234.5678
From x, y <---- Here is the detailed label
--------------
Here From x, y
means "The result is calculated from x and y". I want to translate this into Chinese:
从 x, y 得出
Until then, I can just use this:
"From \(someVariable)"
with a file of lines:
"From" = "从 得出";
And this is how I will use it in code
"\(NSLocalizedString("From", comment: "")) \(someVariable)"
But if this were used in the Chinese version, the final line would be:
"从 得出 x, y"
I mean, I can put 从
and 得出
in two different entries in the line file. But is there a better way to do this?
source to share
You can use %@
in Swift String(format:...)
, it can be replaced with Swift String
or any instance of a subclass NSObject
. 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
%f
for double floating point numbers:
"From %f, %f" = "从 %f, %f 得出";
from
let text = String(format: NSLocalizedString("From %f, %f", comment: ""), x, y)
See Niklas' answer for an even better solution that localizes the numeric representation as well.
source to share
In object C, if we want lines added at runtime like below
John Appleseed is the name
YourLocalizable.strings
"theStringToDisplay" = "%@ is the name";
ViewController.m
NSString *username = @"John Appleseed";
NSString *messageBeforeFormat = NSLocalizedStringFromTable(@"theStringToDisplay", @"YourLocalizable", nil);
NSString *messageAfterFormat = [NSString stringWithFormat:messageBeforeFormat, username ];
self.yourLabel.text = messageAfterFormat;
Further explanation in this nice post
https://www.oneskyapp.com/academy/learn-ios-localization/2-format-strings-plurals/
source to share