英文:
How should I handle localization of string which contains multiple variables and some of them should take care of plural
问题
以下是要翻译的内容:
For example:
let count: Int = ...
let unit: Calendar.Component = ... //.year, .month, .day
let str = "\(count) \(unit) later";
So str
could be one of these:
//In English
1 year later
3 months later
//In Chinese(Note: The spaces between the words are being removed.)
1年后
3个月后
What's the best way to localize this string? If the unit
part is removed, I know how to do that with stringsdict file, but now I am confused.
英文:
For example:
let count: Int = ...
let unit: Calendar.Component = ... //.year, .month, .day
let str = "\(count) \(unit) later"
So str
could be one of these:
//In English
1 year later
3 months later
//In Chinese(Note: The spaces between the words are being removed.)
1年后
3个月后
What's the best way to localize this string? If the unit
part is removed, I know how to do that with stringsdict file, but now I am confused.
答案1
得分: 1
代码部分不提供翻译。
英文:
The use of stringsdict works just fine for this case. You just need an entry for each possible unit.
The English setup would include something like:
<key>years later</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@years@</string>
<key>years</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%d year later</string>
<key>other</key>
<string>%d years later</string>
</dict>
</dict>
<key>months later</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@months@</string>
<key>months</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%d month later</string>
<key>other</key>
<string>%d months later</string>
</dict>
</dict>
<key>days later</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@days@</string>
<key>days</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%d day later</string>
<key>other</key>
<string>%d days later</string>
</dict>
</dict>
Then your code becomes something like:
let count: Int = ...
let unit: Calendar.Component = ... //.year, .month, .day
var key: String?
switch unit {
case .year: key = "years later"
case .month: key = "months later"
case .day: key = "days later"
default: break
}
if let key {
let fmt = NSLocalizedString(key)
let str = String(format: fmt, count)
}
If you might have a bunch of these, it might help to add an extension to Calendar.Component
to create a string from a unit so you don't need to scatter the clumsy switch
statements everywhere.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论