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

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


当前回答

现有答案的变体:

斯威夫特5.1:

extension String {

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

}

然后你可以简单地使用它,带或不带注释:

"Goodbye".localized()
"Hello".localized(withComment: "Simple greeting")

请注意,genstring不能用于此解决方案。

其他回答

Swift 3版本:)…

import Foundation

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

扩展:

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

使用:“_YOUR_STRING_NAME_ .localized ()

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

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

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

通过使用这种方式,可以为不同类型创建不同的实现(即Int或自定义类,如CurrencyUnit,…)也可以使用genstrings实用程序扫描这个方法调用。 只需将例程标志添加到命令中

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

扩展:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

用法:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

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

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