Swift NSLocale编程常量

问题描述 投票:0回答:1

有没有更好的方法来编码,而不使用魔术“en”,“es”字符串?

 let pre = Locale.preferredLanguages[0]
 if pre == "en"
    ....
  else if pre == "es"
    ....
  else if pre == "xx"
    ....

我想要得到编译时错误,而不是犯错,这会更好

 let pre = Locale.preferredLanguages[0]
 if pre == NSLocale.something.ENGLISH
    ....
  else if pre == NSLocale.something.SPANISH
    ....
  else if pre == //and so on
    ....

但我找不到任何东西。

这是正确的代码方式吗?

ios swift internationalization
1个回答
0
投票

对于您计划在应用中支持的语言,请创建一个枚举,将preferredLanguages映射到枚举大小写。下面的剪辑添加了英语和西班牙语的案例。

// Create an enum that maps known language "Strings" to a case statement.
public enum LanguageMap : String{
    // Add a case for all the languages you app will support
    case English = "en"
    case Spanish = "es"
}

扩展Locale以添加一个属性,该属性将返回[LanguageMap]对象而不是[String]

// Extend the Locale class to return

extension Locale{
    public static var preferredLanguageMap : [LanguageMap] {
        let langMap = Locale.preferredLanguages.flatMap({return LanguageMap.init(rawValue: $0) })
        return langMap
    }
}

在您的应用程序中,将if-else语句替换为switch case语句。

// Your application Logic.

switch Locale.preferredLanguageMap.first! {

case .English :
    print("Do Something the English Way")

case .Spanish :
    print("Do Something the Spanish Way")

default:
    print("Do Anything... Throw an error/Default Handling.")
    // Note : Locale.availableIdentifiers has 789 language identifiers till date.
    // This could also change in the future.
    // Ensure you have some default logic for all 'other languages' here.
}
© www.soinside.com 2019 - 2024. All rights reserved.