Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
private class Localizer {
static let sharedInstance = Localizer()
lazy var localizableDictionary: NSDictionary! = {
if let path = Bundle.main.path(forResource: "Localizable", ofType: "plist") {
return NSDictionary(contentsOfFile: path)
}
fatalError("Localizable file NOT found")
}()
func localize(string: String) -> String {
var localizableGroup = localizableDictionary!
let components = string.components(separatedBy: ".") // The char '.' separates group information. E.g. "Market.Fruit.orange"
for component in components {
guard let localizedValue = localizableGroup[component] as? NSDictionary else {
if let localizedString = localizableGroup[component] as? String {
// When the localizable is a String item
return localizedString
}
assertionFailure("Missing translation for: \(string)")
return ""
}
localizableGroup = localizedValue
}
// When the localizable is a Dictionary with at least a 'value' item
guard let localizedString = localizableGroup["value"] as? String else {
assertionFailure("Missing translation for: \(string)")
return ""
}
return localizedString
}
}
extension String {
var localized: String {
return Localizer.sharedInstance.localize(string: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment