swift 我应该如何处理本地化的字符串,其中包含多个变量,其中一些应该照顾复数

jvlzgdj9  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(101)

例如:

let count: Int = ...
let unit: Calendar.Component = ...  //.year, .month, .day
let str = "\(count) \(unit) later"

所以str可能是其中之一:

//In English
1 year later
3 months later

//In Chinese(Note: The spaces between the words are being removed.)
1年后
3个月后

本地化这个字符串的最好方法是什么?如果unit部分被删除,我知道如何用stringsdict文件来做,但现在我很困惑。

relj7zay

relj7zay1#

stringsdict的使用在这种情况下效果很好。您只需要为每个可能的单元创建一个条目。
英语设置将包括如下内容:

<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>

然后你的代码变成这样:

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)
}

如果您可能有一堆这样的语句,那么为Calendar.Component添加一个扩展以从单元创建字符串可能会有所帮助,这样您就不需要到处散布笨拙的switch语句。

相关问题