Return static default value when localization key does not exist

Viewed 544

How can I return a static string (i.e. "AAA") when I am passing a key to NSLocalizedString() that does not exist in the localization file? I could only find information on how to fall back to a default language but not how to return a hardcoded string in case the key does not exist in the localization file.

This code works for me but I need a fallback option:

let localizationKey = "articles_label_" + type.lowercased()
let localizedValue = localizationKey.localized
1 Answers

NSLocalizedString() takes a parameter value which is returned if no localized string is found in the table for the given key.

I infer that localized is a computed property added in a String extension. Something like that :

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: "MyTable", bundle: Bundle.main, comment: "")
    }
}

If you want to add a default value, you should transform this computed property into a function.

extension String {
    func localized(defaultValue: String? = nil) -> String {
        return NSLocalizedString(self, tableName: "MyTable", bundle: Bundle.main, value: defaultValue ?? self, comment: "")
    }
}

And use it like that:

let localizationKey = "articles_label_" + type.lowercased()
let localizedValue = localizationKey.localized(defaultValue: "AAA")
Related