是否有一个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

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


当前回答

为总是忽略“comment”的情况创建了一个小的helper方法。更少的代码更容易阅读:

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

只要把它放在任何地方(类之外),Xcode就会找到这个全局方法。

其他回答

NSLocalizedString也存在于Swift的世界中。

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

tableName、bundle和value参数用默认关键字标记,这意味着在调用函数时可以忽略这些参数。在本例中,将使用它们的默认值。

这导致一个结论,方法调用可以简化为:

NSLocalizedString("key", comment: "comment")

Swift 5 -没有变化,仍然像那样工作。

扩展:

 extension String {
    func localized(comment: String = "") -> String {
        return NSLocalizedString(self, comment: comment)
    }
  }

使用:“_YOUR_STRING_NAME_ .localized ()

也许最好的方法是这个。

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仍然可以工作 你可以添加更多的扩展,比如每个视图控制器一个扩展来保持整洁

为总是忽略“comment”的情况创建了一个小的helper方法。更少的代码更容易阅读:

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

只要把它放在任何地方(类之外),Xcode就会找到这个全局方法。

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

这是一个简单的版本,可以扩展到不同的用例(例如使用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")