如何为目标语言制作 CFLocale?
How do I make a CFLocale for a target language?
在Objective C中,可以如下创建一个CFLocale(取自2012年的this post):
CFLocaleRef myLocale = CFLocaleCopyCurrent()
表示当前语言环境;或者:
CFLocaleRef myLocale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("ja"))
,用于目标语言环境。语言环境名称来自 ISO 639-1/639-2 table, which Apple specifies as their standard for language codes here.*
最右边的列
*注意:非常古老的代码示例指的是长语言代码,如'Japanese',may be expected [=] 38=] OS X 大于 10.4.
如何在 Swift 3 中创建 CFLocale,因为 API 似乎在几个方面发生了变化?
以下是自 2012 年给出的 Objective-C 示例以来 API 对 Swift 的更改:
- CFLocaleRef 已替换为 CFLocale.
- CFStringRef 已替换为 CFString,它可能由常规 String 创建转换为 CFString 类型:
"ja" as CFString!
.
- CFLocaleCreate() now expects a CFLocaleIdentifier rather than just a CFString, so we must provide one using CFLocaleCreateCanonicalLanguageIdentifierFromString().
这可以通过以下两行来完成:
let localeIdentifier: CFLocaleIdentifier = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, "ja" as CFString!)
let locale: CFLocale = CFLocaleCreate(kCFAllocatorDefault, localeIdentifier)
CFLocale
toll-free 桥接到 NSLocale
,因此您只需调用
let myLocale = NSLocale(localeIdentifier: "ja")
// or
let myLocale = NSLocale(localeIdentifier: NSLocale.canonicalLocaleIdentifier(from: "Japanese"))
取决于您是否拥有 ISO 639-1 语言代码。
对应Swift3"overlay value type"Locale
(由 Calendar
、DateFormatter
、...使用,
比较 SE-0069 Mutability and Foundation Value Types)
同样可以用
创建
let myLocale = Locale(identifier: "ja")
// or
let myLocale = Locale(identifier: Locale.canonicalIdentifier(from: "Japanese"))
在Objective C中,可以如下创建一个CFLocale(取自2012年的this post):
CFLocaleRef myLocale = CFLocaleCopyCurrent()
表示当前语言环境;或者:CFLocaleRef myLocale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("ja"))
,用于目标语言环境。语言环境名称来自 ISO 639-1/639-2 table, which Apple specifies as their standard for language codes here.* 最右边的列
*注意:非常古老的代码示例指的是长语言代码,如'Japanese',may be expected [=] 38=] OS X 大于 10.4.
如何在 Swift 3 中创建 CFLocale,因为 API 似乎在几个方面发生了变化?
以下是自 2012 年给出的 Objective-C 示例以来 API 对 Swift 的更改:
- CFLocaleRef 已替换为 CFLocale.
- CFStringRef 已替换为 CFString,它可能由常规 String 创建转换为 CFString 类型:
"ja" as CFString!
. - CFLocaleCreate() now expects a CFLocaleIdentifier rather than just a CFString, so we must provide one using CFLocaleCreateCanonicalLanguageIdentifierFromString().
这可以通过以下两行来完成:
let localeIdentifier: CFLocaleIdentifier = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, "ja" as CFString!)
let locale: CFLocale = CFLocaleCreate(kCFAllocatorDefault, localeIdentifier)
CFLocale
toll-free 桥接到 NSLocale
,因此您只需调用
let myLocale = NSLocale(localeIdentifier: "ja")
// or
let myLocale = NSLocale(localeIdentifier: NSLocale.canonicalLocaleIdentifier(from: "Japanese"))
取决于您是否拥有 ISO 639-1 语言代码。
对应Swift3"overlay value type"Locale
(由 Calendar
、DateFormatter
、...使用,
比较 SE-0069 Mutability and Foundation Value Types)
同样可以用
let myLocale = Locale(identifier: "ja")
// or
let myLocale = Locale(identifier: Locale.canonicalIdentifier(from: "Japanese"))