Я создал это расширение для String для управления локализацией моих приложений. Вы можете просто использовать его как "history".localized
, чтобы получить локализованную строку.
Чтобы применить замены, используйте метод "my string %@".localized(withSubstitutions: "my substitution")
Вы можете нарезать и нарезать кубиками, чтобы использовать то, что вы хотите от расширения.
Я также поддерживал 2 константы let sameInBothLanguages: [String]
& let needTranslationsFor: [String]
, чтобы вести учет, если есть строки, которые не следует локализовать, потому что они одинаковы на обоих языках, или для отправки команде по контенту для перевода.
extension String {
var localized: String {
return localized(from: nil)
}
func localized(withSubstitutions substitutions: String...) -> String {
return String(format: self.localized, arguments: substitutions)
}
func localized(from table: String?) -> String {
let translatedString = getTranslatedString(fromTable: table)
// No sense looking up the string in Release builds
#if !DEBUG
return translatedString
#endif
guard Locale.current.languageCode == "en" else {
return translatedString
}
let otherLanguage = "es"
// We can keep adding to this list temporarily in order to make the app actually run. Every so often we will give this list to the content team and empty it once we get the translations back.
let otherLanguageString = getTranslatedString(fromTable: table, inLanguage: otherLanguage)
if otherLanguageString == self &&
!sameInBothLanguages.contains(self) &&
!needTranslationsFor.contains(self) {
//swiftlint:disable:next no_nslocalizedstring
assertionFailure("No Spanish version of localized string found for '\(self)'. Please go to String+SA.swift and add this string to either the 'needTranslationsFor' or 'sameInBothLanguages' array.")
}
return translatedString
}
private func getTranslatedString(fromTable table: String?, inLanguage language: String) -> String {
if let path = Bundle.main.path(forResource: language, ofType: "lproj"),
let otherLanguageBundle = Bundle(path: path) {
let otherLanguageString = getTranslatedString(fromTable: table, andBundle: otherLanguageBundle)
return otherLanguageString
}
return self
}
private func getTranslatedString(fromTable table: String?, andBundle bundle: Bundle = Bundle.main) -> String {
let translatedString = bundle.localizedString(forKey: self, value: self, table: table)
return translatedString
}
}