前几天我问过如何获取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”错误是什么意思?我一直在尝试和搜索它,但我还没有找到解决方案:/
百万谢谢:)
答案 0 :(得分: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)
}
答案 1 :(得分: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
答案 2 :(得分: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")
答案 3 :(得分:0)
对于swift3
let identifier = Locale.identifier(fromComponents: [NSLocale.Key.countryCode.rawValue:countryCode])
答案 4 :(得分:0)
尝试:
(已编辑)使用语言环境,而不是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
}