Skip to content

Instantly share code, notes, and snippets.

@kvdesa
Created January 12, 2022 19:13
Show Gist options
  • Save kvdesa/7351c729af9e951087ccd40ac8501e14 to your computer and use it in GitHub Desktop.
Save kvdesa/7351c729af9e951087ccd40ac8501e14 to your computer and use it in GitHub Desktop.
Localization - Fallback to English

Overview

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.

Explanation

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.

Code

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)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment