-1

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?

Community
  • 1
  • 1
Jamie Birch
  • 5,839
  • 1
  • 46
  • 60

2 Answers2

1

Here are the API changes to Swift since the Objective-C example given from 2012:

This can be done with the following two lines:

let localeIdentifier: CFLocaleIdentifier = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, "ja" as CFString!)
let locale: CFLocale = CFLocaleCreate(kCFAllocatorDefault, localeIdentifier)
Jamie Birch
  • 5,839
  • 1
  • 46
  • 60
1

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"))
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382