是否有一个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
但是,它很长,一点也不方便。
我已经创建了自己的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文件中。
也许这不是最简单的方法,但这是可能的。
通过使用这种方式,可以为不同类型创建不同的实现(即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 :)")
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 -没有变化,仍然像那样工作。