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

Ios SWIFT中类似于UIColor.systemgray的任何标准字符串,ios,swift,string,Ios,Swift,String,在Android中,我们可以访问平台提供的一些标准字符串资源,例如取消,确定,删除等。这很方便,因为我不必存储这些简单文本的所有翻译 我知道Swift提供了类似UIColor的功能,例如UIColor.systemgray 我的问题是:除了String之外,还有类似的东西吗。谢谢 不,Swift中没有此类静态属性您可以从苹果自己的框架中加载本地化字符串。例如,要从UIKit加载,您可以使用 let bundle = Bundle(for: UIView.self) let string = bu

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

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


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

不,Swift中没有此类静态属性

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

let bundle = Bundle(for: UIView.self)
let string = bundle.localizedString(forKey: "Cancel", value: nil, table: nil)
当当前区域设置为德语时,将显示“Abbrechen”

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

我能想到的最好的解决方法是定义您自己使用的键,并通过单元测试持续验证它们

例如,您可以在一个case iterable枚举中收集所有系统字符串键

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包,用于方便地探索和访问系统包中的可用字符串。不过也有一些警告。有关更多信息,请参阅