SWIFT中类似UIColor.systemgray的任何标准字符串



在Android中,我们可以访问平台提供的一些标准字符串资源,例如cancelOKdelete等。这很方便,因为我不必存储那些简单文本的所有翻译。

我知道Swift提供了类似UIColor的东西,例如UIColor.systemgray.

我的问题是:除了String,还有类似的东西吗。谢谢

从技术上讲,您可以从苹果自己的框架加载本地化字符串。例如,要从UIKit加载,您需要使用

let bundle = Bundle(for: UIView.self)
let string = bundle.localizedString(forKey: "Cancel", value: nil, table: nil)

当当前区域设置为德语时,这将给出"Abbrechen"

这种方法的缺点是,您只能在运行时知道框架中是否存在特定的字符串。

我能想到的最好的解决方法是定义你自己使用的密钥,并通过单元测试不断验证它们。

例如,您可以在可迭代枚举中收集所有系统字符串键

public enum SystemStringKey: String, CaseIterable {
case cancel = "Cancel"
...
}

并使用它们通过String上的扩展加载系统字符串

public extension String {
static var systemStringBundle: Bundle {
return Bundle(for: UIView.self)
}
static func systemString(for key: SystemStringKey) -> String {
return systemStringBundle.localizedString(forKey: key.rawValue, value: nil, table: nil)
}
}

在代码中,您可以使用类似常量的系统字符串

label.text = .systemString(for: .cancel)

为了验证它们的持续存在,你可以使用一个单元测试,比如这个

class SystemStringKeyTests: XCTestCase {
func testAllKeysExist() throws {
let path = try XCTUnwrap(String.systemStringBundle.path(forResource: "Localizable", ofType: "strings"))
let dict = try XCTUnwrap(NSDictionary(contentsOfFile: path))
for key in SystemStringKey.allCases {
XCTAssertNotNil(dict[key.rawValue])
}
}
}

这并不是100%防弹的,因为苹果在iOS更新中删除了一个字符串,然后任何依赖该字符串的发布应用程序都会显示未翻译的英文字符串,直到你自己发布更新。


更新:我组装了一个Swift包,用于方便地探索和访问系统捆绑包中的可用字符串。不过也有一些注意事项。看见https://nosuchdomain.mooo.com/git/doc/swift-systemstrings了解更多信息。

不,Swift 中没有这样的静态属性

最新更新