Search code examples
swiftmacosappkit

Why does NSLocale.current.identifier include currency on macOS?


If I request the current locales identifier on iOS, it returns just the identifier string:

let identifier = NSLocale.current.identifier // en_GB

However, on macOS 10.12.2 it also returns the currency:

let identifier = NSLocale.current.identifier // en_GB@currency=GBP

Is this a bug or expected behaviour?


Solution

  • I think the best option for me here is to generate the code myself. To help with this I have created an extension on Locale:

    extension Locale {
        var iso3166code: String {
            guard
                let language = languageCode,
                let region = regionCode
                else { return "en-US" }
            return "\(language)-\(region)"
        }
    }
    

    While this is accurate enough for my purposes, you should probably ensure it returns expected values for your project.