2

几天前我问过如何在 Swift 中获取国家列表,你解决了它的第一部分(这里:Swift - Get list of countries),但我无法获得最终的国家列表,因为它给出了一个错误:

var countries: NSMutableArray = NSMutableArray()
countries = NSMutableArray(capacity: (NSLocale.ISOCountryCodes().count))
for countryCode : AnyObject in NSLocale.ISOCountryCodes() {
  let dictionary : NSDictionary = NSDictionary(object:countryCode, forKey:NSLocaleCountryCode)
  let identifier : NSString     = NSLocale.localeIdentifierFromComponents(dictionary)
  // next line - fatal error: Can't unwrap Optional.None
  let country    : NSString     = 
    NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: identifier)
  countries.addObject(country)
}
println(countries)

“致命错误:无法打开 Optional.None”错误是什么意思?我一直在尝试和搜索它,但我还没有找到解决方案:/

百万谢谢:)

4

5 回答 5

2

此行是一个可选字符串

  let identifier : NSString = NSLocale.localeIdentifierFromComponents(dictionary)

用。。。来代替

  let identifier : NSString? = NSLocale.localeIdentifierFromComponents(dictionary)

接着

if identifier {
  let country : NSString = 
     NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: identifier!)   
 countries.addObject(country)
}
于 2014-06-24T11:45:07.283 回答
0

我遇到同样的问题,这是我的代码

for countryCodes : AnyObject in NSLocale.ISOCountryCodes() {
    let dictionary : Dictionary = [NSLocaleCountryCode: countryCodes]
    let identifier : String? = NSLocale.localeIdentifierFromComponents(dictionary)
    if let id = identifier {
        let country : String = NSLocale(localeIdentifier: "en_GB").displayNameForKey(NSLocaleIdentifier, value: id)
        countries.append(country)
    }
}

或从 更改NSLocale.currentLocale()NSLocale(localeIdentifier: "en_GB")

于 2014-07-03T09:45:17.437 回答
0

试试这个:D

var countries : String[] = Array()
for countryCodes : AnyObject in NSLocale.ISOCountryCodes() {
        let dictionary : NSDictionary = NSDictionary(object:countryCodes, forKey:NSLocaleCountryCode)
        let identifier : NSString? = NSLocale.localeIdentifierFromComponents(dictionary)
        if identifier {
            let country : NSString = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: identifier!)
            countries.append(country)
        }
    }
println(countries)

我认为这个代码可以帮助您获得国家/地区列表:D

于 2014-07-03T02:48:17.953 回答
0

对于 swift3

let identifier = Locale.identifier(fromComponents: [NSLocale.Key.countryCode.rawValue:countryCode])
于 2017-07-10T10:39:01.160 回答
0

尝试这个:

(已编辑)使用 Locale,而不是 NSLocale

func getCountriesList()->[String]{
    var countries = [String]()
    for code in Locale.isoRegionCodes {
        let id = Locale.identifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        if let name = Locale(identifier: id).localizedString(forRegionCode: code) {
            countries.append(name)
        }
    }
    return countries
}
于 2018-10-24T09:21:18.083 回答