Last active
April 3, 2018 18:25
-
-
Save cjlarsen/6961a52bd0a3b07337eab1f4322483e0 to your computer and use it in GitHub Desktop.
Swift 4 update for https://medium.com/@dcordero/a-different-way-to-deal-with-localized-strings-in-swift-3ea0da4cd143
This file contains hidden or 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 { | |
guard let localizedValue = localizableDictionary[string] as? NSDictionary else { | |
assertionFailure("Missing translation for: \(string)") | |
return "" | |
} | |
guard let localizedString = localizedValue["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