Skip to content

Instantly share code, notes, and snippets.

@ethanhuang13
Created March 23, 2017 03:46
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ethanhuang13/6cb3ee2d36eed228cc090962fc1929c3 to your computer and use it in GitHub Desktop.
Save ethanhuang13/6cb3ee2d36eed228cc090962fc1929c3 to your computer and use it in GitHub Desktop.
Detect string language with Swift
//: Playground - noun: a place where people can play
//
// The result is not guaranteed to be accurate. Typically, the function requires 200-400 characters to reliably guess the language of a string.
// Reference: [CFStringTokenizerCopyBestStringLanguage(_:_:)](https://developer.apple.com/reference/corefoundation/1542136-cfstringtokenizercopybeststringl)
//
import Foundation
extension String {
func guessLanguage() -> String {
let length = self.utf16.count
let languageCode = CFStringTokenizerCopyBestStringLanguage(self as CFString, CFRange(location: 0, length: length)) as String? ?? ""
let locale = Locale(identifier: languageCode)
return locale.localizedString(forLanguageCode: languageCode) ?? "Unknown"
}
}
let names = ["明日香", "碇真嗣", "綾波零", "拓跋玉兒", "陳靖仇", "于小雪"]
for name in names {
print("\(name) - \(name.guessLanguage())")
}
@leochen0818
Copy link

let locale = Locale(identifier: languageCode)這行會報錯噢,可能要改成 let locale = Locale.init(identifier: languageCode)會比較好一點

@s4cha
Copy link

s4cha commented May 22, 2017

This is absolutely awesome !!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment