-
-
Save cmorigaki/d96f6260da4ac8d6c2ae78917bc939e4 to your computer and use it in GitHub Desktop.
Localizable plist with group support from https://medium.com/@dcordero/a-different-way-to-deal-with-localized-strings-in-swift-3ea0da4cd143 based on cjlarsen Swift 4 update https://gist.github.com/cjlarsen/6961a52bd0a3b07337eab1f4322483e0
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
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