What's NSLocalizedString equivalent in Swift?

RaffAl picture RaffAl · Aug 1, 2014 · Viewed 109.9k times · Source

Is there an Swift equivalent of NSLocalizedString(...)? In Objective-C, we usually use:

NSString *string = NSLocalizedString(@"key", @"comment");

How can I achieve the same in Swift? I found a function:

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

However, it is very long and not convenient at all.

Answer

dr OX picture dr OX · Apr 1, 2015

I use next solution:

1) create extension:

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

2) in Localizable.strings file:

"Hi" = "Привет";

3) example of use:

myLabel.text = "Hi".localized

enjoy! ;)

--upd:--

for case with comments you can use this solution:

1) Extension:

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

2) in .strings file:

/* with !!! */
"Hi" = "Привет!!!";

3) using:

myLabel.text = "Hi".localized(withComment: "with !!!")