Stacks Image 5

Localized Strings Tips

This year I started using SwiftLint to improve the quality of my swift source code.

The most frequent warning I receive from this tool is the line_length one: 'Line Length Violation: Line should be 120 characters or less'

As many of those warnings where on lines using the NSLocalizedString macro, I had to think about how to improve my way of internationalizing applications.

I used to call the localization macro directly where it was needed, like

playButton.setTitle(NSLocalizedString("PLAY_BUTTON", comment: "Play button"), for: .normal)

which required 91 characters, not counting leading characters for indentation.

Now I create a LocalizedString class with static computed variables.

final class LocalizedString {  
    static var playButton: String {
      return NSLocalizedString("PLAY_BUTTON", comment: "Play button")  
    }  
}

It is used like that:

playButton.setTitle(LocalizedString.playButton, for: .normal)

The instruction in the controller is now 61 characters long, 30 characters less than before. A quick and easy win.

This is also very usefull when the localized string is used as a format:

  static func finishedDialogMsg(level: String, duration: String) -> String {  
    let format = NSLocalizedString("FINISHED_DIALOG_MSG_FORMAT", comment: "You've finished this %@ grid in %@")  
    return String(format: format, level, duration)  
  }  

Instead of having two lines in the controller, only one is required, which also works against the file_length rule of swiftlint, which states that a file should no be longer than 400 lines.

In the previous example you could even give the duration as a TimeInterval (floating number representing a number of elapsed seconds) and perform the conversion to a string representation of the duration directly into the finishedDialogMsg, same thing when you work with dates.

Other benefits of using a LocalizedString class:

  • reduce code duplication when a localized string is used multiple times
  • reduce risk of having mispelled a localized string key as all keys are only written once.

By the way, I found the article app-localization-tips-with-swift quite good, but does not help with formats and I think using an enum + a function uses more characters than a static var in a class.