Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Created November 14, 2023 20:10
Show Gist options
  • Save lucianoschillagi/c07f0653edfee16643f467203dda44dc to your computer and use it in GitHub Desktop.
Save lucianoschillagi/c07f0653edfee16643f467203dda44dc to your computer and use it in GitHub Desktop.
Recognizing the language in a text
import SwiftUI
import NaturalLanguage
struct LangRecognizerView: View {
@State private var text = ""
@State private var currentLangLegend = ""
@State private var currentLang = ""
var body: some View {
VStack {
TextField("Write here", text: $text)
.font(.system(size: 56))
.bold()
Spacer()
VStack {
Text(currentLangLegend)
.font(.system(size: 30))
.multilineTextAlignment(.center)
if currentLangLegend == "Unrecognized language" {
EmptyView()
} else {
Text(currentLang)
.font(.system(size: 46, weight: .bold))
.multilineTextAlignment(.center)
.overlay {
LinearGradient(
colors: [.red, .blue],
startPoint: .leading,
endPoint: .trailing
)
.mask(
Text(currentLang)
.font(Font.system(size: 46, weight: .bold))
.multilineTextAlignment(.center)
)
}
}
}
.bold()
.foregroundColor(.blue)
.fontDesign(.rounded)
Spacer()
Button("Recognize the language") {
recognizeTextLang()
}
.buttonStyle(.borderedProminent).font(.title)
}.padding(25)
}
func recognizeTextLang() {
// Create a language recognizer
let recognizer = NLLanguageRecognizer()
recognizer.processString(text)
// Identify the dominant language
if let language = recognizer.dominantLanguage {
let langString = language.rawValue
switch langString {
case "en":
currentLangLegend = "Your text is written in"
currentLang = "english"
case "es":
currentLangLegend = "Tu texto está escrito en"
currentLang = "español"
case "tr":
currentLangLegend = "Metniniz şu şekilde yazılmıştır:"
currentLang = "türkçe"
case "it":
currentLangLegend = "Il tuo testo è scritto"
currentLang = "italiano"
default:
currentLangLegend = "Unrecognized language"
}
} else {
print("Language not recognized")
}
}
}
#Preview {
LangRecognizerView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment