Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private let bundle = Bundle.main
- private let tableName = "Localizable"
- private let cachedEnglishLocalizations: [String: String] = {
- let bundleURL = bundle.bundleURL as CFURL
- let bundle = CFBundleCreate(nil, bundleURL)
- let cfTableName = "Localizable" as CFString
- let fileExtension = "strings" as CFString
- let englishBundleDirName = "En" as CFString
- guard let url = CFBundleCopyResourceURLForLocalization(
- bundle, cfTableName, fileExtension, nil, englishBundleDirName
- ) else {
- fatalError()
- }
- let plistData = try! Data(contentsOf: url as URL)
- let englishLocalizations = try! PropertyListDecoder().decode(
- [String: String].self, from: plistData)
- return englishLocalizations
- }()
- extension String {
- func localize() -> String {
- let localizedString = NSLocalizedString(
- self, tableName: tableName, bundle: bundle, value: "", comment: ""
- )
- if localizedString == self, let englishVersion = cachedEnglishLocalizations[self] {
- // fall back to English version
- return englishVersion
- } else {
- return localizedString
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement