Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

ios - How to format localised strings in Swift?

I am learning to localise my app to Simplified Chinese. I am following this tutorial on how to do this.

Because the tutorial is based on Obj-C, 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 to be placed there. We have string interpolation right?

My app is kind of related to maths. And I want to display which input(s) is used to compute the result in a detailed label of a table view cell. For example

--------------
1234.5678
From x, y <---- Here is the detailed label
--------------

Here, From x, y means "The result is computed from x and y". I want to translate this to Chinese:

从 x, y 得出

Before, I can just use this:

"From (someVariable)"

with the strings file:

"From" = "从 得出";

And this is how I would use it in code

"(NSLocalizedString("From", comment: "")) (someVariable)"

But if this were used in the Chinese version, the final string will be like this:

"从 得出 x, y"

I mean I can put the and 得出 in two different entries in the strings file. But is there a better way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...