Translating text within your app
At a glance
| Item | Summary |
|---|---|
| Purpose | Display simple system translations and create custom translation experiences. |
| App architecture | One multiplatform SwiftUI target. TranslatingTextApp creates one @Observable ViewModel and injects it into the environment. ContentView is a navigation list of seven independent demo screens: two use the system translation sheet, three use translationTask with a TranslationSession, and two check or download languages. |
| Main patterns | Environment injection of one shared observable object, plus local @State and bindings in each demo view. |
| Project style | TranslatingText/ with ViewModel/ (state and the language value type) and Views/ grouped as SystemUI/, CustomUI/<demo>/, and Availability/<demo>/. |
| Execution model | Swift concurrency: translationTask closures and async view-model methods. Several methods start unretained Task { @MainActor in ... } blocks. ViewModel itself has no actor annotation. |
| State/event model | @Observable properties on ViewModel read through @Environment; @State configuration values whose creation or invalidate() triggers the translationTask; SwiftUI bindings for the sheet and pickers. |
| Key frameworks/packages | SwiftUI, Translation, Foundation. The project declares no Swift package. |
Project structure
TranslatingText.xcodeproj/ one app target: iOS/iPadOS 18.0 and native macOS 15.0
TranslatingText/
├── TranslatingTextApp.swift @main, owns ViewModel, .environment(model)
├── ContentView.swift NavigationStack list of demos
├── ViewModel/
│ ├── ViewModel.swift @Observable shared state and translation helpers
│ └── AvailableLanguage.swift Identifiable, Comparable language value
└── Views/
├── RowView.swift list row
├── SystemUI/ ViewTranslationView, ReplaceTranslationView
├── CustomUI/ SingleString/, Batch/, BatchAsSequence/
└── Availability/ LanguageAvailability/, PrepareTranslation/
Structure observations
- The single application target supports
iphoneos iphonesimulator macosxwith Mac Catalyst turned off (TranslatingText.xcodeproj/project.pbxproj:441,TranslatingText.xcodeproj/project.pbxproj:442), and deploys to iOS 18.0 and macOS 15.0 (TranslatingText.xcodeproj/project.pbxproj:432,TranslatingText.xcodeproj/project.pbxproj:435). That matches the DocC platform list. - Each demo lives in its own folder and file and is reached only from
ContentView(TranslatingText/ContentView.swift:15). Demos do not share navigation state. - Only three demos read the shared
ViewModel:BatchOfStringsView,BatchAsSequenceView, andLanguageAvailabilityView. The other four keep all state in local@State.
Overall architecture
flowchart LR
App["TranslatingTextApp"] --> Model["ViewModel (@Observable)"]
App --> Content["ContentView (NavigationStack)"]
Content --> SysUI["ViewTranslationView / ReplaceTranslationView"]
Content --> Single["SingleStringView"]
Content --> Batch["BatchOfStringsView / BatchAsSequenceView"]
Content --> Avail["LanguageAvailabilityView / PrepareTranslationView"]
SysUI --> Sheet["translationPresentation (system sheet)"]
Single --> Task["translationTask -> TranslationSession"]
Batch --> Task
Batch -. "@Environment" .-> Model
Avail -. "@Environment" .-> Model
Model --> LA["LanguageAvailability"]
Reference code
TranslatingText/TranslatingTextApp.swift:12 — app-level ownership and environment injection
@main
struct TranslatingTextApp: App {
@State private var model = ViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environment(model)
}
}
}Interpretation
Observed: the app is a catalog of independent demos. The Translation APIs are reached in two ways: view modifiers (translationPresentation, translationTask) inside views, and LanguageAvailability plus TranslationSession calls inside ViewModel. The session object is always created by the framework and handed to a translationTask closure; no type stores it.
Inference: the shared ViewModel is a convenience for demos that need list data (foodItems) or the supported-language list, not a per-screen view model. The name suggests MVVM, but most screens do not use it, so this document describes it as a shared observable state owner.
Ownership and state
classDiagram
TranslatingTextApp *-- ViewModel : @State model
BatchOfStringsView o-- ViewModel : @Environment
BatchAsSequenceView o-- ViewModel : @Environment
LanguageAvailabilityView o-- ViewModel : @Environment
ViewModel *-- AvailableLanguage : availableLanguages
SingleStringView *-- Configuration : @State configuration
BatchOfStringsView *-- Configuration : @State configuration
PrepareTranslationView *-- Configuration : @State configuration
Ownership evidence
TranslatingText/ViewModel/ViewModel.swift:11 — shared observable state and its loader
@Observable
class ViewModel {
var translatedText = ""
var isTranslationSupported: Bool?
// German food items ("Salad", "Fries", and "Soup")
var foodItems = ["Salat 🥗", "Fritten 🍟", "Suppe 🍜"]
// ...
var availableLanguages: [AvailableLanguage] = []
init() {
prepareSupportedLanguages()
}
func prepareSupportedLanguages() {
Task { @MainActor in
let supportedLanguages = await LanguageAvailability().supportedLanguages
availableLanguages = supportedLanguages.map {
AvailableLanguage(locale: $0)
}.sorted()
}
}
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
TranslatingTextApp |
ViewModel (model) |
Creates it in @State private var and injects it (TranslatingText/TranslatingTextApp.swift:12, TranslatingText/TranslatingTextApp.swift:17) |
ViewModel methods; views call reset() directly |
ViewModel |
foodItems |
Replaced by translateAllAtOnce and reset() (TranslatingText/ViewModel/ViewModel.swift:65, TranslatingText/ViewModel/ViewModel.swift:20) |
ViewModel |
ViewModel |
availableLanguages |
Filled once by the task started in init (TranslatingText/ViewModel/ViewModel.swift:33) |
ViewModel, inside Task { @MainActor in } |
ViewModel |
isTranslationSupported |
Set by checkLanguageSupport(from:to:) and cleared by reset() (TranslatingText/ViewModel/ViewModel.swift:108) |
ViewModel |
| Each custom-UI view | TranslationSession.Configuration? |
@State private var; created on the first tap, then invalidate()d on later taps (TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:15, TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:43) |
The owning view |
SingleStringView |
sourceText, targetText |
Local @State; the translationTask closure writes targetText (TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:34) |
SingleStringView |
ReplaceTranslationView |
originalText |
Local @State, bound to the text field and replaced by the sheet’s replacement closure (TranslatingText/Views/SystemUI/ReplaceTranslationView.swift:27) |
ReplaceTranslationView |
Observed: ViewModel.translatedText, translate(text:using:), and translateSequence(using:) are defined but never called in this source tree. BatchAsSequenceView’s task calls translateAllAtOnce(using:) (TranslatingText/Views/CustomUI/BatchAsSequence/BatchAsSequenceView.swift:34), so the “Batch as a Sequence” screen currently runs the same all-at-once code path as the “Batch All at Once” screen.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Framework-managed task | .translationTask(configuration) { session in ... } |
SwiftUI runs the action when the configuration is set or invalidated and supplies the TranslationSession |
TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:28, TranslatingText/Views/Availability/PrepareTranslation/PrepareTranslationView.swift:30 |
| Re-trigger by invalidation | configuration?.invalidate() |
A second tap invalidates the existing configuration instead of replacing it | TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:45 |
Main-actor task from init |
Task { @MainActor in ... } in prepareSupportedLanguages() |
Writes availableLanguages on the main actor; the task is not stored or cancelled |
TranslatingText/ViewModel/ViewModel.swift:31 |
| Unawaited inner task | func translateAllAtOnce(using:) async whose body is Task { @MainActor in ... } |
The method returns right after creating the task, so the translationTask action can finish before the translation does; the inner task writes foodItems on the main actor |
TranslatingText/ViewModel/ViewModel.swift:56, TranslatingText/ViewModel/ViewModel.swift:57 |
| Nonisolated async write | checkLanguageSupport(from:to:) async on an unannotated class |
Writes the observable isTranslationSupported from a method that is not main-actor isolated by declaration |
TranslatingText/ViewModel/ViewModel.swift:102, TranslatingText/ViewModel/ViewModel.swift:108 |
| View-created task | .onChange(of:) { Task { await performCheck() } } |
An unstored task per selection change | TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:58 |
| Compiler checking level | SWIFT_VERSION = 5.0, no strict-concurrency setting |
Swift 5 language mode; these isolation crossings are not fully diagnosed | TranslatingText.xcodeproj/project.pbxproj:446 |
Reference code
TranslatingText/ViewModel/ViewModel.swift:56 — an async method that returns before its work completes
extension ViewModel {
func translateAllAtOnce(using session: TranslationSession) async {
Task { @MainActor in
let requests: [TranslationSession.Request] = foodItems.map {
// Map each item into a request.
TranslationSession.Request(sourceText: $0)
}
do {
let responses = try await session.translations(from: requests)
foodItems = responses.map {
// Update each item with the translated result.
$0.targetText
}
} catch {
// Handle any errors.
}
}
}
}Observed: no lock, actor type, or queue protects ViewModel. Main-actor writes are explicit only inside the Task { @MainActor in } blocks. Inference: if you adapt this code, awaiting the work directly inside the translationTask closure (as SingleStringView does) keeps the session’s use within the action’s lifetime, and annotating ViewModel with @MainActor would make every observable write main-actor isolated.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| Shared state | @Observable ViewModel |
Views that read foodItems, availableLanguages, or isTranslationSupported update when they change |
TranslatingText/ViewModel/ViewModel.swift:11, TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:43 |
| Environment injection | .environment(model) and @Environment(ViewModel.self) |
The app supplies the instance; three views read it | TranslatingText/TranslatingTextApp.swift:17, TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:12 |
| Bindings | $showTranslation, $originalText, $selectedFrom, $selectedTo |
Drive the system sheet, the editable text, and the language pickers | TranslatingText/Views/SystemUI/ReplaceTranslationView.swift:20, TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:27 |
| Change trigger | .onChange(of: selectedLanguagePair) with an Equatable LanguagePair |
Runs an availability check when either picker changes | TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:57 |
| Framework import | Translation |
TranslationSession, LanguageAvailability, and the translation view modifiers |
TranslatingText/ViewModel/ViewModel.swift:9, TranslatingText/Views/SystemUI/ViewTranslationView.swift:9 |
| Framework import | SwiftUI |
App, views, environment | TranslatingText/TranslatingTextApp.swift:8 |
| Package declaration | None | The project file declares no Swift package | TranslatingText.xcodeproj/project.pbxproj:446 |
LanguagePair declares its two properties with @State even though it is a plain struct, not a View (TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:80). Its custom == compares the wrapped values, which is what onChange uses.
Class and protocol design
classDiagram
class ViewModel {
<<Observable>>
foodItems
availableLanguages
isTranslationSupported
translateAllAtOnce(session)
checkLanguageSupport(source, target)
}
class AvailableLanguage {
<<struct>>
locale
localizedName()
}
AvailableLanguage ..|> Identifiable
AvailableLanguage ..|> Comparable
LanguagePair ..|> Equatable
ViewModel *-- AvailableLanguage
LanguageAvailabilityView --> LanguagePair
Reference code
TranslatingText/ViewModel/AvailableLanguage.swift:10 — a value type that sorts by localized name
struct AvailableLanguage: Identifiable, Hashable, Comparable {
var id: Self { self }
let locale: Locale.Language
// ...
private func shortName() -> String {
"\(locale.languageCode ?? "")-\(locale.region ?? "")"
}
static func <(lhs: AvailableLanguage, rhs: AvailableLanguage) -> Bool {
return lhs.localizedName() < rhs.localizedName()
}
}| Type | Responsibility | Depends on |
|---|---|---|
TranslatingTextApp |
Creates and injects ViewModel |
SwiftUI |
ViewModel |
Shared demo data, the supported-language list, batch translation, and availability checks, grouped in // MARK: extensions |
Translation |
AvailableLanguage |
Identifiable, sortable wrapper around Locale.Language for pickers |
Foundation |
| System-UI views | Present the system sheet, optionally replacing text | translationPresentation |
| Custom-UI views | Own a configuration and translate in translationTask |
TranslationSession |
PrepareTranslationView |
Calls prepareTranslation() to request a language download |
TranslationSession |
The sample defines no protocols. Types adopt standard library and SwiftUI protocols only.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
TranslatingTextApp.model (TranslatingText/TranslatingTextApp.swift:12) |
@State private |
Only the app struct can replace the instance | Inference: one owner; views receive it through the environment. |
View @State properties such as configuration, showTranslation, sourceText (TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:12, TranslatingText/Views/SystemUI/ViewTranslationView.swift:13) |
@State private |
Local to each view | Inference: each demo is self-contained. |
startTranslation(), performCheck() (TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:43, TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift:70) |
private |
Callable only inside the view | Inference: button and change handlers are the only callers. |
AvailableLanguage.shortName() (TranslatingText/ViewModel/AvailableLanguage.swift:25) |
private |
Hidden formatting helper | Inference: callers use localizedName(). |
ViewModel properties and methods (TranslatingText/ViewModel/ViewModel.swift:13) |
implicit internal |
Any view can read and write foodItems or call reset() |
Inference: a small single-module demo with no private(set) boundary. |
ViewTranslationView.originalText (TranslatingText/Views/SystemUI/ViewTranslationView.swift:16) |
implicit internal var |
Can be set through the memberwise initializer | Inference: lets a caller pass different text, though ContentView uses the default. |
Reference code
TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:43 — private trigger that creates or invalidates the configuration
struct SingleStringView: View {
// ...
private func startTranslation() {
guard configuration == nil else {
configuration?.invalidate()
return
}
// Let the framework automatically determine the language pairing.
configuration = .init()
}
}The meaningful boundaries are Swift private on view state and helpers. ViewModel exposes all of its state as implicitly internal and mutable.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| System translation sheet | ViewTranslationView, ReplaceTranslationView |
Only a binding and the text are needed; the replacement closure writes back the result (TranslatingText/Views/SystemUI/ReplaceTranslationView.swift:27). |
| Single-string translation | SingleStringView’s translationTask closure |
Translates and stores the result directly in view state (TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift:31). |
| Language pairing | Each custom-UI view’s startTranslation() |
SingleStringView lets the framework choose (.init()); the batch views fix German to English (TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:46). |
| Batch translation | ViewModel.translateAllAtOnce(using:) |
Maps foodItems into requests and replaces the array with responses (TranslatingText/ViewModel/ViewModel.swift:58). |
| Streaming batch (defined, unused) | ViewModel.translateSequence(using:) |
Uses clientIdentifier to map each streamed response back to its index (TranslatingText/ViewModel/ViewModel.swift:87). |
| Availability check | ViewModel.checkLanguageSupport(from:to:) |
Maps .installed/.supported to true and .unsupported to false (TranslatingText/ViewModel/ViewModel.swift:106). |
| Language download | PrepareTranslationView |
Calls prepareTranslation() only after the button sets buttonTapped (TranslatingText/Views/Availability/PrepareTranslation/PrepareTranslationView.swift:35). |
| Demo reset | ViewModel.reset() |
Called from views’ onAppear, onDisappear, and Reset buttons (TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:37). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| SwiftUI environment injection | .environment(model) (TranslatingText/TranslatingTextApp.swift:17) and @Environment(ViewModel.self) (TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift:12) |
One app-owned instance reaches any screen without initializer plumbing. Screens that do not need it simply do not declare it. |
| Binding-based state propagation | translationPresentation(isPresented: $showTranslation, ...) and TextField(..., text: $originalText, ...) (TranslatingText/Views/SystemUI/ReplaceTranslationView.swift:20, TranslatingText/Views/SystemUI/ReplaceTranslationView.swift:27); pickers bound to $selectedFrom/$selectedTo |
Framework-presented UI reads and writes view-owned state through bindings. |
Removed from the draft: “Model-View-ViewModel”. The source has one shared @Observable class named ViewModel that only three of seven screens use, and four screens keep their logic in the view itself. That is shared observable state with environment injection, not a per-screen MVVM structure.
Naming conventions
- Views end in
Viewand name the demo, not the API (SingleStringView,BatchOfStringsView,PrepareTranslationView). Folder names repeat the demo name (CustomUI/SingleString/SingleStringView.swift). - Folders group by user-facing category (
SystemUI,CustomUI,Availability), matching theSectionheaders inContentView. ViewModelmethods are verb phrases with the session as an argument label:translateAllAtOnce(using:),translateSequence(using:),checkLanguageSupport(from:to:).- Booleans use
is…/show…(isTranslationSupported,showTranslation,buttonTapped).
Architecture takeaways
TranslationSessionis never stored. A@StateConfigurationis the trigger: create it to run the task the first time, and callinvalidate()to run it again.- System UI (
translationPresentation) needs only a binding; custom UI (translationTask) gives you a session to call yourself. - Keep session use inside the
translationTaskclosure.translateAllAtOncestarts an unawaited task, so itsasyncsignature does not tell the caller when the work ends. - One environment-injected
@Observableobject is enough shared state for a demo catalog; per-screen state stays in@State. clientIdentifieris the source-visible way to match streamed batch responses to requests, even though that method is not wired to a screen in this version.
Source map
| Source file | Relevant symbols |
|---|---|
TranslatingText/TranslatingTextApp.swift |
TranslatingTextApp, model |
TranslatingText/ContentView.swift |
ContentView |
TranslatingText/ViewModel/ViewModel.swift |
ViewModel, prepareSupportedLanguages(), translateAllAtOnce(using:), translateSequence(using:), checkLanguageSupport(from:to:) |
TranslatingText/ViewModel/AvailableLanguage.swift |
AvailableLanguage |
TranslatingText/Views/SystemUI/ViewTranslationView.swift |
ViewTranslationView |
TranslatingText/Views/SystemUI/ReplaceTranslationView.swift |
ReplaceTranslationView |
TranslatingText/Views/CustomUI/SingleString/SingleStringView.swift |
SingleStringView, startTranslation() |
TranslatingText/Views/CustomUI/Batch/BatchOfStringsView.swift |
BatchOfStringsView |
TranslatingText/Views/CustomUI/BatchAsSequence/BatchAsSequenceView.swift |
BatchAsSequenceView |
TranslatingText/Views/Availability/LanguageAvailability/LanguageAvailabilityView.swift |
LanguageAvailabilityView, LanguagePair |
TranslatingText/Views/Availability/PrepareTranslation/PrepareTranslationView.swift |
PrepareTranslationView |
TranslatingText.xcodeproj/project.pbxproj |
Supported platforms, deployment targets, Swift version |