我已经为
Objective-c找到了答案,但我很难在swift中做到这一点.
let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String print(countryCode) // printing for example US
尝试做这样的事情:
原文链接:https://www.f2er.com/swift/319421.html// 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来解决这个问题.