Search code examples
swiftswift3localecore-foundation

How do I make a CFLocale for a target language?


In Objective C, one can create a CFLocale as follows (taken from this post in 2012):

  • CFLocaleRef myLocale = CFLocaleCopyCurrent() for the current locale; or:

  • CFLocaleRef myLocale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("ja")), for a target locale. The locale name comes from the rightmost column of the ISO 639-1/639-2 table, which Apple specifies as their standard for language codes here.*

*Note: very old code examples refer to long language codes like 'Japanese', as may be expected by versions of Mac OS X older than 10.4.

How does one create a CFLocale in Swift 3, as the API appears to have changed in several ways?


Solution

  • CFLocale is toll-free bridged to NSLocale, so you can simply call

     let myLocale = NSLocale(localeIdentifier: "ja")
     // or
     let myLocale = NSLocale(localeIdentifier: NSLocale.canonicalLocaleIdentifier(from: "Japanese"))
    

    depending on whether you have a ISO 639-1 language code or not.

    The corresponding Swift 3 "overlay value type" Locale (which is used by Calendar, DateFormatter, ..., compare SE-0069 Mutability and Foundation Value Types) can similarly be created with

    let myLocale = Locale(identifier: "ja")
    // or 
    let myLocale = Locale(identifier: Locale.canonicalIdentifier(from: "Japanese"))