damus

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

LocalizationUtil.swift (1345B)


      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     if locale == nil {
     12         return Bundle.main
     13     }
     14 
     15     let path = Bundle.main.path(forResource: locale!.identifier, ofType: "lproj")
     16     return path != nil ? (Bundle(path: path!) ?? Bundle.main) : Bundle.main
     17 }
     18 
     19 func localizedStringFormat(key: String, locale: Locale?) -> String {
     20     let bundle = bundleForLocale(locale: locale)
     21     let fallback = bundleForLocale(locale: Locale(identifier: "en-US")).localizedString(forKey: key, value: nil, table: nil)
     22     return bundle.localizedString(forKey: key, value: fallback, table: nil)
     23 }
     24 
     25 /**
     26  Removes the variant part of a locale code so that it contains only the language code.
     27  */
     28 func localeToLanguage(_ locale: String) -> String? {
     29     if #available(iOS 16, *) {
     30         return Locale.LanguageCode(stringLiteral: locale).identifier(.alpha2)
     31     } else {
     32         return NSLocale(localeIdentifier: locale).languageCode
     33     }
     34 }
     35 
     36 /// Returns a localized string that is pluralized based on a single Int-typed count variable.
     37 func pluralizedString(key: String, count: Int, locale: Locale = Locale.current) -> String {
     38     let format = localizedStringFormat(key: key, locale: locale)
     39     return String(format: format, locale: locale, count)
     40 }