Files
damus/damus/Util/LocalizationUtil.swift
Terry Yiu 8a9e3ea76b Fix localization issues and export strings for translation
Changelog-Fixed: Fix localization issues and export strings for translation
Signed-off-by: Terry Yiu <git@tyiu.xyz>
Signed-off-by: William Casarin <jb55@jb55.com>
2023-07-14 09:34:29 -07:00

41 lines
1.3 KiB
Swift

//
// LocalizationUtil.swift
// damus
//
// Created by Terry Yiu on 2/24/23.
//
import Foundation
func bundleForLocale(locale: Locale?) -> Bundle {
if locale == nil {
return Bundle.main
}
let path = Bundle.main.path(forResource: locale!.identifier, ofType: "lproj")
return path != nil ? (Bundle(path: path!) ?? Bundle.main) : Bundle.main
}
func localizedStringFormat(key: String, locale: Locale?) -> String {
let bundle = bundleForLocale(locale: locale)
let fallback = bundleForLocale(locale: Locale(identifier: "en-US")).localizedString(forKey: key, value: nil, table: nil)
return bundle.localizedString(forKey: key, value: fallback, table: nil)
}
/**
Removes the variant part of a locale code so that it contains only the language code.
*/
func localeToLanguage(_ locale: String) -> String? {
if #available(iOS 16, *) {
return Locale.LanguageCode(stringLiteral: locale).identifier(.alpha2)
} else {
return NSLocale(localeIdentifier: locale).languageCode
}
}
/// Returns a localized string that is pluralized based on a single Int-typed count variable.
func pluralizedString(key: String, count: Int, locale: Locale = Locale.current) -> String {
let format = localizedStringFormat(key: key, locale: locale)
return String(format: format, locale: locale, count)
}