skip to content

Strings and Locale Formatting

Text looks up LocalizedStringKey in String Catalogs, plurals come from the catalog, and the environment locale drives formatting and right-to-left. Interviewers ask what breaks in Arabic.

on this pageshow

explore

questions

5

In SwiftUI, why does Text("Welcome back") show a translation while Text(hotelName) with a String variable does not, and what does Text(verbatim:) do?

level: juniorimportance: must knowfreq 76%

answer

  1. the argument's static type decides
  2. ExpressibleByStringLiteral on the key type
  3. StringProtocol overload skips the lookup
  4. verbatim opts a literal out

basics

~20 s

A string literal passed to Text becomes a LocalizedStringKey and is looked up in the app's strings; a String variable selects the StringProtocol initializer and is shown as written. Text(verbatim:) shows a literal without any lookup.

solid answer

~40 s

`Text` has two relevant initializers. `init(_:tableName:bundle:comment:)` takes a `LocalizedStringKey`, and because that type is `ExpressibleByStringLiteral`, a literal like `Text("Welcome back")` lands there: SwiftUI looks the key up in the default table of the main bundle and shows the key itself when no translation exists. A `String` variable matches `init<S: StringProtocol>(_:)` instead, which never localizes, the right behaviour for data such as a hotel name. `Text(verbatim:)` is the explicit opt-out for a literal, such as a booking reference. Interpolation keeps a literal localized: `Text("Your stay at \(hotelName)")` looks up `"Your stay at %@"`. To localize a key known only at runtime, wrap it in `LocalizedStringKey(_:)`, accepting that Xcode cannot extract it.

code

swift · 16 lines
swift
import SwiftUI

struct HotelHeader: View {
    let hotelName: String        // from the booking API, never translated
    let promoKey: String         // a catalog key chosen at runtime

    var body: some View {
        VStack(alignment: .leading) {
            Text("Welcome back")                  // literal: LocalizedStringKey, looked up
            Text(hotelName)                       // String variable: shown verbatim
            Text(verbatim: "Ref: BK-2041")        // literal, deliberately not looked up
            Text(LocalizedStringKey(promoKey))    // runtime key: looked up, never extracted
            Text("Your stay at \(hotelName)")     // key "Your stay at %@"
        }
    }
}

go deeper

for a junior

Recall the one-line rule: a literal in Text is a localized key, a String variable is shown as written, and verbatim: opts a literal out.

for a middle

Explain the mechanism: overload resolution on the argument's type, LocalizedStringKey's literal and interpolation conformances, and the key shown when no translation exists.

for a senior

Show where the rule bites in real code: constants and model properties typed String, runtime keys Xcode cannot extract, and data that must never be translated.

for a principal

Turn the rule into a team convention: which call forms review accepts for interface copy, when verbatim: is legitimate, and how runtime keys get catalog entries.

## Two initializers behind one call site SwiftUI's `Text` has several initializers, and two of them decide whether a string is translated: - **`init(_:tableName:bundle:comment:)`** takes a **`LocalizedStringKey`**. SwiftUI uses the key to look up a translation in a strings table, by default the default table of the **main bundle**. - **`init<S: StringProtocol>(_:)`** takes any `String` or `Substring` and displays it **as written**, with no lookup. The compiler picks between them by the argument's static type. `LocalizedStringKey` conforms to `ExpressibleByStringLiteral` (and `ExpressibleByStringInterpolation`), so a **string literal** such as `Text("Welcome back")` becomes a key and lands on the localizing initializer. A **`String` variable** already has the type `String`, so it matches the `StringProtocol` overload. Apple's documentation for `LocalizedStringKey` states the rule directly: use a literal when you want localization and a variable when you do not; a variable usually holds a user-provided value. The same split runs through other views. `Label`, `Button`, `Toggle`, `Picker` and many more take a `LocalizedStringKey` title and offer a `StringProtocol` overload beside it. ## What each form does | Call | Initializer chosen | Looked up? | Typical use | |---|---|---|---| | `Text("Welcome back")` | `init(_:tableName:bundle:comment:)` | Yes | Interface copy | | `Text(hotelName)` | `init<S: StringProtocol>(_:)` | No | Server or user data | | `Text(verbatim: "Ref: BK-2041")` | `init(verbatim:)` | No | A literal that must never be translated | | `Text(LocalizedStringKey(promoKey))` | `init(_:tableName:bundle:comment:)` | Yes | A key known only at runtime | When `Text` cannot perform the localization, Apple's documentation says it displays the key itself. That is why source-text keys such as `"Welcome back"` are common in SwiftUI: an untranslated screen still reads as English rather than as an identifier. ## Interpolation stays on the localized path Interpolating into a literal does **not** switch localization off. `LocalizedStringKey` has its own `StringInterpolation` type, and each interpolated value becomes a **format specifier** in the key. `Text("Your stay at \(hotelName)")` looks up the key `"Your stay at %@"`, and the hotel name is substituted into whatever the German or Arabic translation says. Translators can move `%@` to wherever their grammar puts it, which is the reason Apple recommends interpolation over gluing pieces together. ## Choosing the right form - **Interface copy** (titles, buttons, empty states): a literal, ideally with a `comment:` for the translator, for example `Text("Explore", comment: "Tab bar item for the Explore screen")`. - **Data** (hotel names, guest names, reviews): pass the `String` variable; it is shown verbatim, which is what you want. - **A literal that is not language** (a booking reference, a sample code): `Text(verbatim:)`, so the string is neither looked up nor offered to translators. - **A key that only arrives at runtime** (a server sends `"promo_summer"`): `Text(LocalizedStringKey(promoKey))`. It works, but Xcode cannot see the key when it builds the String Catalog, so someone must add the entry by hand. ## Tables, bundles and comments on the same initializer The localizing initializer has three optional parameters beyond the key: - **`tableName:`** names a strings table other than the default `Localizable`, which lets a large app split copy by feature. - **`bundle:`** names the bundle to search. `nil`, the default, means the main bundle, which is right for app code but not for code that ships in its own resource bundle, such as a Swift package. - **`comment:`** is a `StaticString` for translators. Xcode copies it next to the key in the String Catalog, so "Book" the button and "Book" the noun can be told apart. Convenience titles on `Label` and `Button` have no `comment:` parameter; when a translator needs context there, pass an explicit `Text("…", comment: "…")` through the view's builder initializer instead. ## Traps that ship English to German users 1. Moving a literal into a `let title = "Welcome back"` constant and passing `title`: the type becomes `String`, the lookup disappears, and nothing warns. 2. Assuming `Text(verbatim:)` is needed for variables; it is not, and wrapping data in `LocalizedStringKey(_:)` instead would try to translate a guest's name. 3. Reading a missing translation as a crash or an empty view: the key is displayed, so the bug is quiet and shows up only in review or in production. The interview signal is the type-driven overload choice: once a candidate says "a literal is a key, a variable is data", the rest follows.

  • How do Button and Label treat a string literal title, and how do you add a translator comment to one?
    Their title initializers also take a `LocalizedStringKey`, so `Label("Message", image: "msgSymbol")` is looked up, while a `String` variable title is shown as written. Those convenience initializers have no `comment:` parameter, so for a comment you use the builder form and pass an explicit `Text("Message", comment: "…")` as the label content.
  • Why should a team not make Text(LocalizedStringKey(someString)) its default pattern?
    The key exists only at runtime, so Xcode's extraction never sees it and no String Catalog entry is created. Missing translations then surface only as untranslated text on a device. Keep it for keys that genuinely arrive at runtime, and add their entries to the catalog by hand.

A hotel clerk reads phrases from a phrasebook in the guest's language but copies the guest's name exactly as written on the booking: literals are phrasebook entries, String variables are names.

  • Text translates any string you pass it, variables included
  • A String variable is looked up if a matching key exists
  • Interpolating a value into a Text literal switches localization off
  • Without verbatim:, a String variable would be sent through the catalog
  • A missing translation makes Text crash or render empty
open as a page

In SwiftUI, how does Text("\(nights) nights") become a String Catalog key, and how does the catalog supply Arabic's plural forms?

level: middleimportance: must knowfreq 62%

basics

~20 s

Interpolating an Int into a Text literal produces the key "%lld nights". The String Catalog stores plural variations for that key per language, and the number picks the category: one and other in English and German, six categories in Arabic.

open as a page

In SwiftUI, what mirrors automatically when the layout direction is right-to-left, and when does an image need flipsForRightToLeftLayoutDirection?

level: middleimportance: should knowfreq 55%

basics

~20 s

In right-to-left, SwiftUI flips each view's x position, so stack order, leading and trailing alignment, padding and edges mirror automatically. Image contents are not mirrored: directional artwork opts in with flipsForRightToLeftLayoutDirection(true), while logos and photos stay unchanged.

open as a page

In a SwiftUI booking app, copy reaches Text through a component's String property and a view model, and those screens stay English in German; why, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Once a literal is stored as String, Text takes the non-localizing StringProtocol overload and Xcode never extracts it. Keep LocalizedStringKey in view parameters, LocalizedStringResource in model code, String(localized:) only where a String is required, and bundle: .module inside packages.

open as a page

As iOS lead of a SwiftUI app shipping in English, German and Arabic, what String Catalog pipeline and release checks do you set, and who owns new strings?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make String Catalogs, one per module, the only source of strings: engineers add commented keys in code, translators work from exports, review enforces localizable types and leading or trailing layout, and releases gate on untranslated counts, pseudolanguage and right-to-left runs.

open as a page