KotaBear233 KotaBear233 - 10 days ago 5
Swift Question

Swift Localization issue

I have this extension:

func localized() -> String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}


It works fine, but if the user changes the language on the phone to one we don't support, the UI will show "example_label". I would like for it default to the english translation if it does not find one for the current iOS language settings.

How can I do this?

Fix:
Not sure if I will use this, not the best code/approach, but this works.
Note: this works for me, because all of my keys contain underscores.

func localized() -> String {
var localizedString = NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
if localizedString.containsString("_") {
let path = NSBundle.mainBundle().pathForResource("en", ofType: "lproj")
let bundle = NSBundle(path: path!)

localizedString = NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
return localizedString
}

Answer

The documentation for this exact function (NSLocalizedString(_:tableName:bundle:value:comment:)) is really lacking, but there's a similar function, localizedString(forKey:value:table:), with complete documentation. It likely acts in a similar way.

value

The value to return if key is nil or if a localized string for key can’t be found in the table.

...

Return Value

A localized version of the string designated by key in table tableName. This method returns the following when key is nil or not found in table:

If key is nil and value is nil, returns an empty string.

If key is nil and value is non-nil, returns value.

If key is not found and value is nil or an empty string, returns key.

If key is not found and value is non-nil and not empty, return value.

According to these rules, with the value set to "" as it is in your function, if the key (self, in this case) isn't found, then the key (self) should be returned. I suspect example_label is coming from some default set somewhere in the rest of your code.

As a side note, I think this function would be nicer if written as a computed property.

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
    }
}