This code is a helper to always try to return the English version of a localized string when it's not found in the current selected language. This is usefull in scenarios where you don't have all Strings localized within the Localized.strings file for a specific language.
When calling localized, the OS tries to find the String inside the Localizable.strings file for the current language. If not found, then it tries to search for the same String inside the English version of Localizable.strings. If that fails, then returns the String itself.
extension String {
var localized: String {
let localizedString = NSLocalizedString(self, value: "NotFound", comment: "")
guard localizedString == "NotFound" else {
return localizedString
}
guard let enPath = Bundle.main.path(forResource: "en", ofType: "lproj"),
let enBundle = Bundle(path: enPath)
else { return self }
return enBundle.localizedString(forKey: self, value: self, table: nil)
}
}