Swift Talking is a blog updated every two weeks about Swift, tooling, Continuous Integration and other stuff written by Alex Salom.

Localize strings more beautifully with an extension

If you’ve worked in an App that has multiple languages you’d probably have learn to hate love Apple’s localization API NSLocalizedString. We just want a localize some strings but instead we are forced to provide a comment which in most cases we’ll just pass in nil.

Checkout the documentation here.

I’ve been using small String extension to reduce the verbosity while keeping the API flexible for different scenarios. Let’s go straight to the point and show some snippets with the implementation and usage.

Implementation:

public extension String {
  public func localize(tableName tableName: String? = nil, bundle: NSBundle = NSBundle.mainBundle(), comment: String = "") -> String {
    return NSLocalizedString(
      self,
      tableName: tableName,
      bundle: bundle,
      value: "",
      comment: comment)
  }
}

Usage:

Basic:

"MENU".localize()
"MENU".localize(comment: "Menu title")

Or if you have other Localizable.strings files:

"MENU".localize(tableName: "SomeOtherLocalizable")

Or if you are in a different target:

"MENU".localize(tableName: "SomeOtherLocalizableAndTarget", bundle: NSBundle(forClass: DummyClass.self))
...
private class DummyClass { }

In the last example I find it useful to just create another extension inside of the target were the Localizable.strings file is located.

extension String {
  func localizeTargetX(comment: String = "") -> String {
    return localize(tableName: "TargetXLocalizable", bundle: Bundle(for: DummyClass.self), comment: comment)
  }
}

private class DummyClass { }

Alex Salom

Hi! My name is Alex Salom and I’m an iOS Engineer. In this site I’ll share with you tricks & tips related to iOS and also to everything that happens around it: tooling, Continuous Integration and Continuous Delivery. You can find me as well in Twitter, GitHub and LinkedIn.