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

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


当前回答

虽然这不能解决缩短的问题,但这帮助我组织消息,我为错误消息创建了一个如下所示的结构

struct Constants {
    // Error Messages
    struct ErrorMessages {
        static let unKnownError = NSLocalizedString("Unknown Error", comment: "Unknown Error Occured")
        static let downloadError = NSLocalizedString("Error in Download", comment: "Error in Download")
    }
}

let error = Constants.ErrorMessages.unKnownError

通过这种方式,您可以组织消息并使genstring工作。

这是使用的genstrings命令

find ./ -name \*.swift -print0 | xargs -0 genstrings -o .en.lproj

其他回答

实际上,你可以在Swift项目中使用两个阶段来翻译你的文本:

1)第一阶段是使用旧的方法来创建所有可翻译的字符串:

NSLocalisedString("Text to translate", comment: "Comment to comment")

1.1)然后你应该使用genstrings生成Localizable.strings:

$ genstrings *swift

2)之后,你应该使用这个答案。

2.1)基于正则表达式使用XCode的“Find and Replace”选项。 对于给定的例子(如果你没有注释),正则表达式将是:

NSLocalizedString\((.*)\, comment:\ \"\"\) 

并将其替换为

$1.localized

或者(如果你有意见的话)

NSLocalizedString\((.*)\, comment:\ (.*)\)

并将其替换为

$1.localizedWithComment(comment: $2)

您可以随心所欲地使用正则表达式和不同的扩展组合。一般的方法是把整个过程分成两个阶段。希望这能有所帮助。

Swift 3版本:)…

import Foundation

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

现有答案的变体:

斯威夫特5.1:

extension String {

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

}

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

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

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

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

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

我使用下一个解决方案:

1)创建扩展:

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

2)本地化。字符串文件:

"Hi" = "Привет";

3)使用实例:

myLabel.text = "Hi".localized

享受吧!;)

——乌利希期刊指南:

对于带有注释的情况,您可以使用此解决方案:

1)扩展:

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

2) .strings文件:

/* with !!! */
"Hi" = "Привет!!!";

3)使用:

myLabel.text = "Hi".localized(withComment: "with !!!")