swift – 从国家/地区代码获取国家/地区名称
发布时间:2020-12-14 05:30:37 所属栏目:百科 来源:网络整理
导读:我已经为 Objective-c找到了答案,但我很难在swift中做到这一点. 我用它来获取当前位置的国家/地区代码: let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String print(countryCode)// printing for example US 但是,如
我已经为
Objective-c找到了答案,但我很难在swift中做到这一点.
我用它来获取当前位置的国家/地区代码: let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String print(countryCode) // printing for example US 但是,如何将此国家/地区代码转换为国家/地区名称,例如将“美国”转换为“美国”?
尝试做这样的事情:
// get the localized country name (in my case,it's US English) let englishLocale : NSLocale = NSLocale.init(localeIdentifier : "en_US") // get the current locale let currentLocale = NSLocale.currentLocale() var theEnglishName : String? = englishLocale.displayNameForKey(NSLocaleIdentifier,value: currentLocale.localeIdentifier) if let theEnglishName = theEnglishName { let countryName = theEnglishName.sliceFrom("(",to: ")") print("the localized country name is (countryName)") } 使用此辅助函数that I found here: import Foundation extension String { func sliceFrom(start: String,to: String) -> String? { return (rangeOfString(start)?.endIndex).flatMap { sInd in (rangeOfString(to,range: sInd..<endIndex)?.startIndex).map { eInd in substringWithRange(sInd..<eInd) } } } } 我通过研究this related question来解决这个问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |