SwiftUI本地化多个字符串插值

huangapple go评论52阅读模式
英文:

SwiftUI localize multiple string interpolations

问题

我想将多个变量传递到我的本地化字符串中。
例如,我想本地化字符串"My Name is \(name) and I am \(age) years old"

要使用单个字符串插值本地化字符串,我可以在我的字符串文件中这样做:
"helloName%@" = "Hello my name is %@";
但是如果我想本地化一个带有两个或更多字符串插值的文本,我该怎么办呢?
请注意,不同语言中的字符串插值将位于不同的位置...
"name%@age%@" = "My Name is %@ and I am @% years old";
这不会起作用,因为您无法区分插入的字符串还是整数,也不知道在翻译后的字符串中应该放在哪里。
有什么想法吗?

英文:

I would like to pass more than one variable into my localized string.
For example I want to localize the string "My Name is \(name) and I am \(age) years old".

To localize a string with a single string interpolation, I can do this in my string file:
"helloName%@" = "Hello my name is %@";
But what can I do if I want to localize a text with two ore more string interpolations?
Note that the string interpolations will be on different positions in different languages...
"name%@age%@" = "My Name is %@ and I am @% years old";
That won´t work because you can't differentiate the interpolated strings or integers and you
don´t know where to put it in the translated string.
Any ideas?

答案1

得分: 0

"helloNameAndAge %@ %lld" = "很容易,只需使用更多的占位符。当然,您需要正确匹配类型:
let name = "Max"
let age = 21
Text("helloNameAndAge \(name) \(age)")
占位符在本地化版本中的位置并不重要。重要的是排序与键中的排序相同。

如果您需要更改排序,请参阅[Formatting Localized Strings with Multiple Values](https://stackoverflow.com/q/51369282)。以下是如何切换您的示例(Swift 代码不变):

"helloNameAndAge %@ %lld" = "我今年%2$lld岁了,我的名字是%1$@。";
P.S. 一个很好的占位符格式参考是[String Format Specifiers](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1)。
英文:

It's easy, just use more placeholders. You need to match the types correctly of course:

"helloNameAndAge %@ %lld" = "My name is %@ and I am %lld years old";
let name = "Max"
let age = 21
Text("helloNameAndAge \(name) \(age)")

The position of the placeholders in the localized versions don't matter. All that matters is that the ordering is the same as in the key.

See Formatting Localized Strings with Multiple Values if you need to change the ordering too. Here is how your example could be switched (the Swift code doesn't change):

"helloNameAndAge %@ %lld" = "I am %2$lld years old, my name is %1$@";

Ps. A good reference for placeholder format is String Format Specifiers.

huangapple
  • 本文由 发表于 2023年6月15日 19:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定