gpt4 book ai didi

ios - Swift NSLocale 编程常量

转载 作者:行者123 更新时间:2023-11-30 11:55:36 25 4
gpt4 key购买 nike

有没有更好的方法来编码而不使用魔术“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
....

但我找不到任何东西。

这是正确的编码方式吗?

最佳答案

对于您计划在应用中支持的语言,创建一个枚举,将首选语言映射到枚举情况。下面的片段添加了英语和西类牙语的情况。

// 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.
}

关于ios - Swift NSLocale 编程常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com