Rutger Huijsmans Rutger Huijsmans - 7 months ago 16
Swift Question

Localizing a string

So I'm localizing a project using an Extension to NSString that I found on SO. That extension looks like this:

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


I however have come across strings in my Localizable.strings list that contain parameters. For example:

"explore_item_desc1" = "Welcome to rent my %1$s!";


Before I was able to do this:

uiLabel.text = "localizedString".localized


How do I do something similar for those strings holding parameters?

Answer

can make your localized variable into a function rather

extension String {
    func localized(args : CVarArgType...) -> String {
        return withVaList(args, { (f:CVaListPointer) -> String in
            (NSString.init(format:NSLocalizedString(self, comment:""), arguments: f) as String)
        })
    }
}

usage

uiLabel.text = "localized_key_name".localized("param1", "param2")

credit