Skip to content

AI Text Translator — Swift source

Translate any text between 24 languages with an LLM — auto-detected or explicit source, straight from your browser with your own free Groq key.

This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// text-translator — AI text translator: prompt building + reply cleanup.
//
// Language: Swift (5, Foundation allowed)
// Source:   CosmoDev polyglot showcase port of the `text-translator` tool,
//           ported from src/lib/translate.ts (the canonical implementation).
// License:  display source — part of CosmoDev's polyglot tool pages.
//
// The portable surface is pure — language list, [system, user] message
// building, reply cleanup. Foundation's NSRegularExpression runs the TS
// port's fence pattern verbatim and Optional<String> carries the TS null.
// Swift counts text.count in grapheme clusters where the TS slice counts
// UTF-16 units; the cut-and-mark shape stays the same.

import Foundation

/// One entry of the curated common-language list.
struct Language {
    let id: String
    let label: String
}

/// One message for the provider layer; role is "system" or "user".
struct ChatMessage {
    let role: String
    let content: String
}

/// Source-language sentinel: let the model detect the input language.
let autoSource = "auto"

/// Sentinel entry shown in the "from" select.
let autoLanguage = Language(id: autoSource, label: "Auto-detect")

/// Curated common-language list — the SSOT for both selects.
let languages = [
    Language(id: "en", label: "English"),    Language(id: "es", label: "Spanish"),
    Language(id: "fr", label: "French"),     Language(id: "de", label: "German"),
    Language(id: "pt", label: "Portuguese"), Language(id: "it", label: "Italian"),
    Language(id: "nl", label: "Dutch"),      Language(id: "sv", label: "Swedish"),
    Language(id: "pl", label: "Polish"),     Language(id: "tr", label: "Turkish"),
    Language(id: "ru", label: "Russian"),    Language(id: "uk", label: "Ukrainian"),
    Language(id: "ar", label: "Arabic"),     Language(id: "fa", label: "Persian"),
    Language(id: "he", label: "Hebrew"),     Language(id: "hi", label: "Hindi"),
    Language(id: "bn", label: "Bengali"),    Language(id: "zh", label: "Chinese"),
    Language(id: "ja", label: "Japanese"),   Language(id: "ko", label: "Korean"),
    Language(id: "vi", label: "Vietnamese"), Language(id: "th", label: "Thai"),
    Language(id: "id", label: "Indonesian"), Language(id: "sw", label: "Swahili"),
]

/// Input cap; longer text is cut and marked so the model knows it ends early.
let maxInputChars = 12_000

/// Label for a known language id; unknown ids pass through (the TS `?? id`).
func languageLabel(_ id: String) -> String {
    languages.first(where: { $0.id == id })?.label ?? id
}

/// Build the [system, user] chat messages for the provider layer.
func buildPromptMessages(_ text: String, from: String, to: String) -> [ChatMessage] {
    let fromPart = from == autoSource
        ? "Detect the source language yourself."
        : "The source language is \(languageLabel(from))."
    let body = text.count > maxInputChars
        ? String(text.prefix(maxInputChars)) + "\n… (text truncated)"
        : text
    let system = "You are a faithful translator. \(fromPart) Translate the user's text "
        + "into \(languageLabel(to)). Output ONLY the translation — no preamble, no notes, "
        + "no backticks, preserving paragraphs, formatting, and code blocks as-is."
    return [
        ChatMessage(role: "system", content: system),
        ChatMessage(role: "user", content: body),
    ]
}

/// Clean the model's reply into displayable translation text. Strips stray
/// markdown fences (``` plus an optional lowercase info-string and newline)
/// and trims; nil only when nothing survives — the TS port's null.
func parseTranslation(_ text: String) -> String? {
    guard let fence = try? NSRegularExpression(pattern: "```[a-z]*\\n?") else { return nil }
    let range = NSRange(text.startIndex..., in: text)
    let cleaned = fence.stringByReplacingMatches(in: text, range: range, withTemplate: "")
        .trimmingCharacters(in: .whitespacesAndNewlines)
    return cleaned.isEmpty ? nil : cleaned
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →