damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

LocalizationUtil.swift (1285B)


      1 //
      2 //  LocalizationUtil.swift
      3 //  damus
      4 //
      5 //  Created by Terry Yiu on 2/24/23.
      6 //
      7 
      8 import Foundation
      9 
     10 func bundleForLocale(locale: Locale) -> Bundle {
     11     let path = Bundle.main.path(forResource: locale.identifier, ofType: "lproj")
     12     return path != nil ? (Bundle(path: path!) ?? Bundle.main) : Bundle.main
     13 }
     14 
     15 func localizedStringFormat(key: String, locale: Locale) -> String {
     16     let bundle = bundleForLocale(locale: locale)
     17     let fallback = bundleForLocale(locale: Locale(identifier: "en-US")).localizedString(forKey: key, value: nil, table: nil)
     18     return bundle.localizedString(forKey: key, value: fallback, table: nil)
     19 }
     20 
     21 /**
     22  Removes the variant part of a locale code so that it contains only the language code.
     23  */
     24 func localeToLanguage(_ locale: String) -> String? {
     25     if #available(iOS 16, *) {
     26         return Locale.LanguageCode(stringLiteral: locale).identifier(.alpha2)
     27     } else {
     28         return NSLocale(localeIdentifier: locale).languageCode
     29     }
     30 }
     31 
     32 /// Returns a localized string that is pluralized based on a single Int-typed count variable.
     33 func pluralizedString(key: String, count: Int, locale: Locale = Locale.current) -> String {
     34     let format = localizedStringFormat(key: key, locale: locale)
     35     return String(format: format, locale: locale, count)
     36 }