gpt4 book ai didi

ios - 如何在 Swift 3 中使用 NSLocale 获取国家代码

转载 作者:IT王子 更新时间:2023-10-29 07:39:23 25 4
gpt4 key购买 nike

请问如何在 Swift 3 中使用 NSLocale 获取国家代码?

这是我以前使用的代码。

NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String

我可以在 Swift 3 中获得如下语言代码。

Locale.current.languageCode!

如我所见,获取 languageCode 很简单,但 countryCode 属性不可用。

最佳答案

您可以在 Locale 结构上使用 regionCode 属性。

Locale.current.regionCode

它没有被记录为旧的 NSLocaleCountryCode 构造的替代品,但它看起来像是。以下代码检查所有已知语言环境的国家/地区代码,并将它们与地区代码进行比较。它们是相同的。

public func ==(lhs: [String?], rhs: [String?]) -> Bool {
guard lhs.count == rhs.count else { return false }

for (left, right) in zip(lhs, rhs) {
if left != right {
return false
}
}

return true
}

let newIdentifiers = Locale.availableIdentifiers
let newLocales = newIdentifiers.map { Locale(identifier: $0) }
let newCountryCodes = newLocales.map { $0.regionCode }

let oldIdentifiers = NSLocale.availableLocaleIdentifiers
newIdentifiers == oldIdentifiers // true

let oldLocales = oldIdentifiers.map { NSLocale(localeIdentifier: $0) }
let oldLocalesConverted = oldLocales.map { $0 as Locale }
newLocales == oldLocalesConverted // true

let oldComponents = oldIdentifiers.map { NSLocale.components(fromLocaleIdentifier: $0) }
let oldCountryCodes = oldComponents.map { $0[NSLocale.Key.countryCode.rawValue] }
newCountryCodes == oldCountryCodes // true

关于ios - 如何在 Swift 3 中使用 NSLocale 获取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596238/

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