Last active
November 14, 2019 16:38
-
-
Save dobaduc/294d278bb7a285c838b8 to your computer and use it in GitHub Desktop.
Tiny useful wrapper function of NSLocalizedString in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// EasyLocalization.swift | |
// | |
// Created by Doba Duc on 9/1/15. | |
// Copyright (c) 2015 Doba Duc. All rights reserved. | |
// | |
/// Tiny useful wrapper function of NSLocalizedString in Swift | |
/// | |
/// @param key Localizable key | |
/// @param replacements (Optional) A dictionary of replacements to be used in a formatted string. | |
/// @return Localized string | |
func lang(key: String, _ replacements: [String: String]? = [:]) -> String { | |
if let dict = replacements { | |
var string = NSLocalizedString(key, comment: "") | |
for (k, v) in dict { | |
string = string.stringByReplacingOccurrencesOfString("#{\(k)}", withString: v) | |
} | |
return string | |
} else { | |
return NSLocalizedString(key, comment: "") | |
} | |
} | |
// Assume that your Localizable.strings file looks like below: | |
// "user.name.format" = "Mr./Ms. #{name}" // Placeholder format: #{<placeholder_key>} | |
// "welcome.text" = "Welcome to Swift world!" | |
// ... | |
// ... | |
// Usage examples: | |
print(lang("welcome.text")) | |
print(lang("user.name.format", ["name": "Smith"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example below shows why we need this wrapper around
NSLocalizedString
andString(format:arguments)
function calls to handle localized texts more efficiently.(Just copy & paste the following code blocks to a playground and see the results)
Handling localized texts as usual
Issue with the code above:
In the example above, we can't just write a single line of code that works for both English and Japanese!
Handling localized texts with the wrapper function
Advantages:
NSLocalizedString
andString(format:arguments)
In short, write 1 single line of code for any languages and let the wrapper handle the rest