How to get country code using NSLocale in Swift 3

前端 未结 6 985
予麋鹿
予麋鹿 2020-12-13 17:31

Could you please help on how to get country code using NSLocale in Swift 3 ?

This is the previous code I have been using.

N         


        
6条回答
  •  执笔经年
    2020-12-13 17:45

    If you make sure that you're using an NSLocale and not a Locale instance, you can use the countryCode property:

    let locale: NSLocale = NSLocale.current as NSLocale
    let country: String? = locale.countryCode
    print(country ?? "no country")
    // > Prints "IE" or some other country code
    

    If you try to use countryCode with a Swift Locale Xcode will give you an error with a suggestion to use regionCode instead:

    let swiftLocale: Locale = Locale.current
    let swiftCountry: String? = swiftLocale.countryCode
    // > Error "countryCode' is unavailable: use regionCode instead"
    

提交回复
热议问题