几天前我问过如何获取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”错误是什么意思?我一直在尝试和搜索它,但我还没有找到解决方案:/
百万谢谢:)
这一行是一个可选字符串
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)
}
尝试这个: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
我和你面临同样的问题,这是我的代码
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")
对于swift3
let identifier = Locale.identifier(fromComponents: [NSLocale.Key.countryCode.rawValue:countryCode])
试试这个:
(编辑)使用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
}