2

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
Dominik
  • 1,703
  • 6
  • 26
  • 46

1 Answers1

2

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")
Johan Drevet
  • 225
  • 2
  • 8
  • Great, that worked for me. I used this code: let labelTitle : String = NSLocalizedString(localizationKey, tableName: nil, bundle: Bundle.main, value: "Artikel", comment: localizationKey) – Dominik Jan 18 '19 at 15:08