问题描述
我正在学习将我的应用本地化为简体中文。我正在关注如何执行。
I am learning to localise my app to Simplified Chinese. I am following this tutorial on how to do this.
由于本教程基于Obj-C,格式化的字符串可以这样写:
Because the tutorial is based on Obj-C, formatted strings can be written like this:
"Yesterday you sold %@ apps" = "Ayer le vendió %@ aplicaciones";
你喜欢? =~Es bueno?〜;
"You like?" = "~Es bueno?~";
但我使用的是Swift。在Swift中,我认为你不能使用%@
来表明那里有东西放在那里。我们有字符串插值吗?
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
--------------
这里,从x,y
表示结果是从x和y计算的。我想把它翻译成中文:
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)"
使用字符串文件:
"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?
推荐答案
你可以使用%@
在Swift的字符串(格式:...)
中,它可以用Swift > String 或 NSObject
子类的任何实例。
例如,如果Localizable.strings文件包含定义
You can use %@
in Swift's String(format:...)
, it can be substitutedby a Swift String
or any instance of a NSObject
subclass.For example, if the Localizable.strings file contains the definition
"From %@, %@" = "从 %@, %@ 得出";
然后
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))
产生从1.2,2.4得出。另一个选择是使用
%f
格式表示双浮点数:
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' answerfor an even better solution which localizes the number representationas well.
这篇关于如何在Swift中格式化本地化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!