是否有一个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
但是,它很长,一点也不方便。
我使用下一个解决方案:
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 !!!")
虽然这不能解决缩短的问题,但这帮助我组织消息,我为错误消息创建了一个如下所示的结构
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
我已经创建了自己的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文件中。
也许这不是最简单的方法,但这是可能的。