- Updated: January 18, 2026
- 6 min read
Swift Command‑Line Translation Tool Brings Chinese‑to‑English on macOS
The new Swift command‑line translation tool for macOS instantly converts Chinese text to English directly in the terminal, leveraging Apple’s native Translation and NaturalLanguage frameworks without any external API keys.
Introduction – A Swift‑Powered CLI for On‑The‑Fly Chinese‑to‑English Translation
macOS developers who spend hours switching between browsers, copy‑pasting snippets into web translators, or opening Spotlight for a quick lookup now have a native, zero‑dependency solution. Built with Swift async/await, OpenAI ChatGPT integration concepts, and the powerful ArgumentParser library, this command‑line utility (named translate) delivers instant, offline translations from Chinese to English—perfect for developers, writers, and anyone who needs rapid language support while coding.
Background – Why macOS Needs a Faster Translation Shortcut
The demand for quick, reliable translation on macOS has grown for three main reasons:
- Multilingual development environments: International teams often share code comments, documentation, and UI strings in Mandarin.
- Privacy‑first workflows: Sending text to cloud APIs can expose proprietary code or confidential data.
- Productivity friction: Opening a browser, pasting text, and waiting for a response adds unnecessary steps to a developer’s workflow.
While macOS already offers a right‑click “Translate” option and Spotlight can perform translations, those features require a mouse click or a separate UI window. A pure CLI tool eliminates the context switch, letting you stay inside Terminal and keep your hands on the keyboard.
Development Journey – From Zig Experiments to a Swift Async/Await Masterpiece
1. Early Prototyping with Zig
The author initially tried to build the translator in ChatGPT and Telegram integration projects using Zig, only to discover that Zig cannot directly call Swift’s async APIs. The attempt highlighted two key lessons:
- Swift’s
TranslationSessionlives in a Swift‑only runtime. - Async functions require a Swift shim or a native Swift binary.
2. Switching to Swift & Setting Up ArgumentParser
Swift was already installed on the author’s Mac, complete with an LSP and formatter. The first code scaffold used Apple’s Telegram integration on UBOS example to demonstrate the ArgumentParser package:
import ArgumentParser
@main
struct Translate: AsyncParsableCommand {
@Argument(help: "Text to translate")
var input: String
func run() async throws { /* … */ }
}
The switch from ParsableCommand to AsyncParsableCommand was crucial because the translation API is asynchronous.
3. Language Detection with NLLanguageRecognizer
Hard‑coding the source language (e.g., zh_CN) worked but broke when the user typed Traditional Chinese. The solution was to employ NLLanguageRecognizer from the AI tools suite:
func detectLanguage(_ text: String) -> Locale.Language? {
let recognizer = NLLanguageRecognizer()
recognizer.processString(text)
guard let lang = recognizer.dominantLanguage else { return nil }
return Locale.Language(identifier: lang.rawValue)
}
4. Handling Model Installation & Availability
macOS stores translation models separately from the UI‑based “Translate” service. The tool checks model status with LanguageAvailability and prompts the user to install missing language packs via System Settings. This mirrors the experience of the built‑in Spotlight translator but keeps everything in the terminal.
5. Final Code Assembly
The final implementation combines async execution, language detection, model verification, and error handling into a concise CLI:
import ArgumentParser
import NaturalLanguage
import Translation
@main
struct Translate: AsyncParsableCommand {
@Argument(help: "Text to translate")
var input: String
func run() async throws {
guard let source = detectLanguage(input) else {
throw ExitCode.failure
}
let target = Locale.Language(identifier: "en_US")
let availability = LanguageAvailability()
let status = await availability.status(from: source, to: target)
switch status {
case .unsupported:
print("❌ Pairing not supported")
throw ExitCode.failure
case .supported:
print("⚠️ Model not installed – open System Settings → Language & Region → Translation Languages")
throw ExitCode.failure
case .installed:
break
@unknown default:
print("❓ Unknown status")
throw ExitCode.failure
}
let session = TranslationSession(installedSource: source, target: target)
try await session.prepareTranslation()
let response = try await session.translate(input)
print("🔤 \(response.targetText)")
}
}
Final Implementation – How the Tool Works, Step by Step
Below is a practical walkthrough of the tool’s execution flow:
- Parse Input:
ArgumentParsercaptures the raw string after the command (e.g.,translate 你好). - Detect Language:
NLLanguageRecognizerdetermines whether the input is Simplified or Traditional Chinese. - Validate Model: The tool queries
LanguageAvailabilityto ensure the Chinese‑English model is installed. - Prepare Session: Calls
session.prepareTranslation()to load the model into memory. - Translate: Executes
session.translate(input)asynchronously and prints the English result.
Example usage:
$ swift run translate 你好世界
> 你好世界
🔤 Hello world
The tool works offline after the language packs are installed, making it ideal for secure environments where network calls are prohibited.
Comparison with Existing Solutions (Spotlight, Web Apps, Third‑Party APIs)
While macOS already offers translation via Spotlight (Cmd+Space) and the right‑click menu, the Swift CLI provides distinct advantages:
| Feature | Spotlight / UI | Third‑Party APIs (Google, DeepL) | Swift CLI Tool |
|---|---|---|---|
| Offline Capability | Requires internet for some languages | Always online | Works offline after model install |
| Privacy | Text sent to Apple servers for some languages | Data leaves your machine | No external calls – fully local |
| Keyboard‑Centric | Mouse/trackpad needed | Browser UI or curl | Pure terminal, 1‑line command |
| Customization | Limited | API parameters, but limited to provider | Open source – extendable with Swift packages |
For developers who already use AI marketing agents or the Workflow automation studio, the CLI can be chained into larger automation pipelines, e.g., translating user‑generated content before feeding it into a sentiment‑analysis model.
Conclusion – Impact and Future Possibilities
The Swift command‑line translation tool demonstrates how native macOS frameworks can replace heavyweight cloud services for everyday developer tasks. By keeping the workflow inside the terminal, it reduces context switching, safeguards data, and showcases the power of Swift’s modern concurrency model.
“Building a CLI with Apple’s own translation stack feels like unlocking a hidden superpower on macOS.” – Developer who built the tool
Looking ahead, the same architecture can be expanded to:
- Support for additional language pairs (e.g., Japanese‑English, Korean‑English).
- Integration with Chroma DB integration for caching frequent translations.
- Voice output via ElevenLabs AI voice integration, turning translated text into spoken audio.
- Embedding the CLI into Web app editor on UBOS for low‑code translation widgets.
Try It Today and Explore More UBOS Resources
Ready to give the tool a spin? Clone the repository, build with swift build, and place the binary in /usr/local/bin. For a step‑by‑step guide, check out the UBOS templates for quick start and adapt the code to your own workflow.
If you’re interested in extending the concept, UBOS offers a suite of AI‑powered services that can complement your translation pipeline:
- AI SEO Analyzer – automatically audit multilingual content.
- AI Article Copywriter – generate localized blog posts.
- AI Video Generator – create subtitles for video assets.
Dive deeper into the UBOS ecosystem with the UBOS platform overview, explore pricing on the UBOS pricing plans, or join the UBOS partner program to co‑create AI‑enhanced developer tools.
The story of this tool’s creation was originally chronicled in a personal blog post. For the full developer diary, see the original article.