是否有一个Swift等效的NSLocalizedString(…)? 在Objective-C中,我们通常使用:

NSString *string = NSLocalizedString(@"key", @"comment");

我如何在Swift中实现同样的目标?我找到了一个函数:

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

但是,它很长,一点也不方便。


当前回答

也许最好的方法是这个。

fileprivate func NSLocalizedString(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

and

import Foundation
extension String {
    static let Hello = NSLocalizedString("Hello")
    static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
    static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}

然后你可以像这样使用它

let message: String = .ThisApplicationIsCreated
print(message)

对我来说这是最好的,因为

硬编码的字符串在一个特定的文件中,所以哪天你想改变它就很容易了 比每次在文件中手动输入字符串更容易使用 Genstrings仍然可以工作 你可以添加更多的扩展,比如每个视图控制器一个扩展来保持整洁

其他回答

当你翻译,说从英语,一个短语是相同的,到另一种语言,它是不同的(因为性别,动词的变化或变化),在Swift中最简单的NSString形式,在所有情况下都是三个参数一。例如,英语短语“previous was”的“weight”(“предыдущий б л”)和“waist”(“предыдущая б ла”)在俄语中的翻译就不一样。

在这种情况下,一个Source需要两种不同的翻译(就WWDC 2018推荐的XLIFF工具而言)。你不能实现它与两个参数NSLocalizedString,其中“previous was”将是相同的“键”和英文翻译(即值)。唯一的方法就是使用三论点形式

NSLocalizedString("previousWasFeminine", value: "previous was", comment: "previousWasFeminine")

NSLocalizedString("previousWasMasculine", value: "previous was", comment: "previousWasMasculine")

其中键(“previousWasFeminine”和“previouswasmasculinity”)是不同的。

我知道一般的建议是将短语整体翻译,然而,有时这太费时和不方便。

我已经创建了自己的genstrings工具,用于使用自定义翻译函数提取字符串

extension String {

    func localizedWith(comment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment)
    }

}

https://gist.github.com/Maxdw/e9e89af731ae6c6b8d85f5fa60ba848c

它将解析所有swift文件,并将代码中的字符串和注释导出到.strings文件中。

也许这不是最简单的方法,但这是可能的。

使用默认语言进行本地化:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

Swift 3版本:)…

import Foundation

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

有助于在单元测试中使用:

这是一个简单的版本,可以扩展到不同的用例(例如使用tableNames)。

public func NSLocalizedString(key: String, referenceClass: AnyClass, comment: String = "") -> String 
{
    let bundle = NSBundle(forClass: referenceClass)
    return NSLocalizedString(key, tableName:nil, bundle: bundle, comment: comment)
}

像这样使用它:

NSLocalizedString("YOUR-KEY", referenceClass: self)

或者像这样加一条评论:

NSLocalizedString("YOUR-KEY", referenceClass: self, comment: "usage description")