Yet another localization in Swift

Internationalisation and Localization of apps is essential when you want the apps to seamlessly support different languages and region. Internationalization refers to process of providing a framework to the app for supporting multiple languages. And Localization refers to the process of making your app to support a particular locale such as Turkish.

What I want in this tutorial is to simplify and make more readable the below statement using extensions regarding the VIPER architecture

func notifyLoginButtonTapped() {
    let viewModel = view?.getLoginViewModel()
    
    if(viewModel != nil) {
    	...
        let message = NSLocalizedString("Processing...", "Processing...")
        view?.displayProgress(message: message)
        interactor?.authenticateUser(model: model)
    }
}

As you remember from my previous posts, VIPER architecture is based on modules targetting reusability. Let’s assume each module has its own .strings file. For instance Login module has a file named Login.strings including all the strings that should be localized, and Address module has Address.strings, so on and so forth.

In short, what I want to do is writing more readable localization statement and obtaining more specialized to viper module. What I want to do is what I did below :)

func notifyLoginButtonTapped() {
    let viewModel = view?.getLoginViewModel()
    
    if(viewModel != nil) {
    	...
        let message = "Processing".localized(in: "Login")
        view?.displayProgress(message: message)
        interactor?.authenticateUser(model: model)
    }
}

Here “Processing” string is localized in according to “Login” module.

let message = "Processing".localized(in: "Login")

How can we achieve this? Write an Extension method for String class as indicated below

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

To summarize, I give a more readable localization example and it can be used with a viper module comfortably of course you may not need to use it in a viper module. If you have just one file named Localizable.strings, you may use without specifying the localization file with a litte bit change in tableName in extension.

let message = "Processing".localized()
comments powered by Disqus