Swift – 获取国家列表
我怎样才能得到一个在Swift中所有国家名称的数组? 我试图转换我在Objective-C中的代码,这是这样的:
if (!pickerCountriesIsShown) { NSMutableArray *countries = [NSMutableArray arrayWithCapacity: [[NSLocale ISOCountryCodes] count]]; for (NSString *countryCode in [NSLocale ISOCountryCodes]) { NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]]; NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier]; [countries addObject: country]; }
在斯威夫特,我不能从这里过去:
if (!countriesPickerShown) { var countries: NSMutableArray = NSMutableArray() countries = NSMutableArray.arrayWithCapacity((NSLocale.ISOCountryCodes).count) // Here gives the Error. It marks NSLocale.ISOCountryCodes and .count
你们有人知道吗?
谢谢
首先, ISOCountryCodes
需要参数括号,而不是ISOCountryCodes()
。 其次,你不需要围绕NSLocale
和ISOCountryCodes()
。 此外,arrayWithCapacity已被弃用,意味着从语言中删除。 这个工作版本会有点像这样
if (!countriesPickerShown) { var countries = NSMutableArray() countries = NSMutableArray(capacity: (NSLocale.ISOCountryCodes().count)) }
这是一个NSLocale的Swift扩展,它返回一个Swift友好的Locale结构数组,它带有国家名和国家代码。 它可以很容易地扩展到包括其他国家的数据。
extension NSLocale { struct Locale { let countryCode: String let countryName: String } class func locales() -> [Locale] { var locales = [Locale]() for localeCode in NSLocale.ISOCountryCodes() { let countryName = NSLocale.systemLocale().displayNameForKey(NSLocaleCountryCode, value: localeCode)! let countryCode = localeCode as! String let locale = Locale(countryCode: countryCode, countryName: countryName) locales.append(locale) } return locales } }
然后很容易得到像这样的国家的数组:
for locale in NSLocale.locales() { println("\(locale.countryCode) - \(locale.countryName)") }
这不是一个财产的操作
if let codes = NSLocale.ISOCountryCodes() { println(codes) }