如何获取 Swift ios 中的国家/地区列表?
How do I get a list of countries in Swift ios?
我已经看到两个与我类似的问题,但这些问题的答案对我不起作用。我有一个旧项目,其中包含在一组方括号内手动输入的国家/地区列表。
我可以在我的 pickerView 中轻松使用它,但我想知道是否有更有效的方法来做到这一点?
我将在 UIPickerView 中使用国家列表。
您可以使用 NSLocale class 的 isoCountryCodes
获取国家/地区列表,其中 returns 是 [String]
的数组。从那里,您可以使用 NSLocale
的 displayName(forKey:)
方法获取国家/地区名称。它看起来像这样:
var countries: [String] = []
for code in NSLocale.isoCountryCodes {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
countries.append(name)
}
print(countries)
和伊恩的一样,但更矮
let countries = NSLocale.ISOCountryCodes().map { (code:String) -> String in
let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
return NSLocale(localeIdentifier: "en_US").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
}
print(countries)
将显示的国家/地区名称本地化也是一个好习惯。因此,除了 vedo27 答案之外,它会是:
let countriesArray = NSLocale.ISOCountryCodes().map { (code:String) -> String in
let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
let currentLocaleID = NSLocale.currentLocale().localeIdentifier
return NSLocale(localeIdentifier: currentLocaleID).displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
}
这是@vedo27 在 Swift 3
中的回答
let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
Swift 3 声明为 var
:
var countries: [String] {
let myLanguageId = "en" // in which language I want to show the list
return NSLocale.isoCountryCodes.map {
return NSLocale(localeIdentifier: myLanguageId).localizedString(forCountryCode: [=10=]) ?? [=10=]
}
}
SWIFT 3 和 4
var countries: [String] = []
for code in NSLocale.isoCountryCodes as [String] {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
countries.append(name)
}
print(countries)
SWIFT 4
这是 Swift 4
中的一种优雅方式
var countries: [String] = {
var arrayOfCountries: [String] = []
for code in NSLocale.isoCountryCodes as [String] {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
arrayOfCountries.append(name)
}
return arrayOfCountries
}()
或者,您可以在 swift 4 中使用系统语言进行本地化。
import Foundation
struct Country {
let name: String
let code: String
}
final class CountryHelper {
class func allCountries() -> [Country] {
var countries = [Country]()
for code in Locale.isoRegionCodes as [String] {
if let name = Locale.autoupdatingCurrent.localizedString(forRegionCode: code) {
countries.append(Country(name: name, code: code))
}
}
return countries
}
}
Swift 4.2
let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: [=10=]) }
let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: [=10=]) }
更新到 vedo27 的回答,但在
Swift 5:
let countries : [String] = NSLocale.isoCountryCodes.map { (code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
还有一个按字母顺序排列的国家排序数组,在获取国家列表后在您的订单下面添加这个
let sortedcountries = countries.sorted { [=11=] < }
Swift 您可以轻松检索国家名称及其国旗表情符号。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var countriesData = [(name: String, flag: String)]()
for code in NSLocale.isoCountryCodes {
let flag = String.emojiFlag(for: code)
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
countriesData.append((name: name, flag: flag!))
}else{
//"Country not found for code: \(code)"
}
}
print(countriesData)
}
}
extension String {
static func emojiFlag(for countryCode: String) -> String! {
func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
return scalar.value >= 0x61 && scalar.value <= 0x7A
}
func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
precondition(isLowercaseASCIIScalar(scalar))
// 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
// 0x61 marks the start of the lowercase ASCII alphabet: 'a'
return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
}
let lowercasedCode = countryCode.lowercased()
guard lowercasedCode.count == 2 else { return nil }
guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }
let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: [=10=]) })
return String(indicatorSymbols.map({ Character([=10=]) }))
}
}
结果:
这是 Swift 5.1 的代码(至少对我有用,因为很多功能都已重命名):
let array = NSLocale.isoCountryCodes.map
{
(code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let currentLocaleID = NSLocale.current.identifier
return NSLocale(localeIdentifier: currentLocaleID).displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
这里的数组是一个[String]
我已经看到两个与我类似的问题,但这些问题的答案对我不起作用。我有一个旧项目,其中包含在一组方括号内手动输入的国家/地区列表。
我可以在我的 pickerView 中轻松使用它,但我想知道是否有更有效的方法来做到这一点?
我将在 UIPickerView 中使用国家列表。
您可以使用 NSLocale class 的 isoCountryCodes
获取国家/地区列表,其中 returns 是 [String]
的数组。从那里,您可以使用 NSLocale
的 displayName(forKey:)
方法获取国家/地区名称。它看起来像这样:
var countries: [String] = []
for code in NSLocale.isoCountryCodes {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
countries.append(name)
}
print(countries)
和伊恩的一样,但更矮
let countries = NSLocale.ISOCountryCodes().map { (code:String) -> String in
let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
return NSLocale(localeIdentifier: "en_US").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
}
print(countries)
将显示的国家/地区名称本地化也是一个好习惯。因此,除了 vedo27 答案之外,它会是:
let countriesArray = NSLocale.ISOCountryCodes().map { (code:String) -> String in
let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
let currentLocaleID = NSLocale.currentLocale().localeIdentifier
return NSLocale(localeIdentifier: currentLocaleID).displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
}
这是@vedo27 在 Swift 3
中的回答 let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
Swift 3 声明为 var
:
var countries: [String] {
let myLanguageId = "en" // in which language I want to show the list
return NSLocale.isoCountryCodes.map {
return NSLocale(localeIdentifier: myLanguageId).localizedString(forCountryCode: [=10=]) ?? [=10=]
}
}
SWIFT 3 和 4
var countries: [String] = []
for code in NSLocale.isoCountryCodes as [String] {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
countries.append(name)
}
print(countries)
SWIFT 4
这是 Swift 4
中的一种优雅方式var countries: [String] = {
var arrayOfCountries: [String] = []
for code in NSLocale.isoCountryCodes as [String] {
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
arrayOfCountries.append(name)
}
return arrayOfCountries
}()
或者,您可以在 swift 4 中使用系统语言进行本地化。
import Foundation
struct Country {
let name: String
let code: String
}
final class CountryHelper {
class func allCountries() -> [Country] {
var countries = [Country]()
for code in Locale.isoRegionCodes as [String] {
if let name = Locale.autoupdatingCurrent.localizedString(forRegionCode: code) {
countries.append(Country(name: name, code: code))
}
}
return countries
}
}
Swift 4.2
let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: [=10=]) }
let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: [=10=]) }
更新到 vedo27 的回答,但在 Swift 5:
let countries : [String] = NSLocale.isoCountryCodes.map { (code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
还有一个按字母顺序排列的国家排序数组,在获取国家列表后在您的订单下面添加这个
let sortedcountries = countries.sorted { [=11=] < }
Swift 您可以轻松检索国家名称及其国旗表情符号。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var countriesData = [(name: String, flag: String)]()
for code in NSLocale.isoCountryCodes {
let flag = String.emojiFlag(for: code)
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
countriesData.append((name: name, flag: flag!))
}else{
//"Country not found for code: \(code)"
}
}
print(countriesData)
}
}
extension String {
static func emojiFlag(for countryCode: String) -> String! {
func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
return scalar.value >= 0x61 && scalar.value <= 0x7A
}
func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
precondition(isLowercaseASCIIScalar(scalar))
// 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
// 0x61 marks the start of the lowercase ASCII alphabet: 'a'
return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
}
let lowercasedCode = countryCode.lowercased()
guard lowercasedCode.count == 2 else { return nil }
guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }
let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: [=10=]) })
return String(indicatorSymbols.map({ Character([=10=]) }))
}
}
结果:
这是 Swift 5.1 的代码(至少对我有用,因为很多功能都已重命名):
let array = NSLocale.isoCountryCodes.map
{
(code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let currentLocaleID = NSLocale.current.identifier
return NSLocale(localeIdentifier: currentLocaleID).displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
这里的数组是一个[String]