skip to content

Text Rendering and Fonts

Text renders strings, Markdown, AttributedString and format styles in fonts sized by text styles. Interviewers ask how a label adapts to size and locale without hand-built strings.

on this pageshow

explore

questions

6

In SwiftUI, why does Text render **Pending** in bold from a string literal but show the asterisks when it comes from a String variable?

level: juniorimportance: must knowfreq 60%

answer

  1. which initializer the compiler picks
  2. literal becomes a LocalizedStringKey
  3. init(verbatim:) and init(_:) for String
  4. AttributedString(markdown:) at runtime

basics

~20 s

A string literal passed to Text becomes a LocalizedStringKey, and SwiftUI parses inline Markdown in it. A String variable goes through Text's plain-string initializer, which shows the characters as they are; parse runtime Markdown with AttributedString(markdown:).

solid answer

~30 s

`Text("**Pending** at _Corner Café_")` picks `init(_:tableName:bundle:comment:)`, which treats the literal as a `LocalizedStringKey`; SwiftUI renders inline Markdown in it: bold, italic, strikethrough, inline code and links. `Text(serverMessage)` with a `String` picks the `StringProtocol` initializer, which neither localizes nor parses, so the asterisks appear. `Text(verbatim:)` does the same for a literal. To style text that arrives at runtime, build `try AttributedString(markdown:options:)` and pass it to `Text`; `.inlineOnlyPreservingWhitespace` keeps its line breaks. Literal Markdown is inline only: `#` headings and `-` lists stay as plain characters.

code

swift · 19 lines
swift
import SwiftUI

struct PendingNotice: View {
    let serverMessage: String   // "**Pending** at _Corner Café_"

    var body: some View {
        VStack(alignment: .leading) {
            Text("**Pending** at _Corner Café_")   // literal: bold and italic
            Text(serverMessage)                    // String: shows the asterisks
            Text(verbatim: "**Pending**")          // verbatim: shows the asterisks
            if let styled = try? AttributedString(
                markdown: serverMessage,
                options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
            ) {
                Text(styled)                       // parsed at runtime: styled
            }
        }
    }
}

go deeper

for a junior

Recall that a literal passed to Text is a LocalizedStringKey and gets inline Markdown, while a String variable is shown as typed, and name init(verbatim:) for literals that must stay literal.

for a middle

Explain why overload resolution picks different initializers for a literal and a String, and show AttributedString(markdown:options:) with a fallback when parsing throws.

for a senior

Spot the review issues: server text turned into localization keys, user content run through a Markdown parser, and block Markdown pushed into one Text that cannot lay it out.

for a principal

Set the boundary a team follows: which text is a key, which is content, and where runtime styling is parsed once into AttributedString instead of being improvised in each view.

## Three initializers, chosen by the compiler `Text` has several initializers that take text, and Swift's overload resolution picks one from the **static type** of the argument: | Call | Initializer | Localized | Markdown parsed | |---|---|---|---| | `Text("**Pending**")` | `init(_:tableName:bundle:comment:)` with a `LocalizedStringKey` | yes | yes, inline | | `Text(message)` where `message: String` | `init(_:)` for `StringProtocol` | no | no | | `Text(verbatim: "**Pending**")` | `init(verbatim:)` | no | no | | `Text(LocalizedStringKey(message))` | the localized initializer | yes | yes, inline | | `Text(attributed)` where `attributed: AttributedString` | `init(_:)` for `AttributedString` (iOS 15) | no | already parsed | A string **literal** is not a `String` until something makes it one. `LocalizedStringKey` is expressible by a string literal, so `Text("…")` builds a key, and Apple's documentation says that initializer looks the key up in the app's strings and shows the key itself when there is no translation. The same key is where SwiftUI reads Markdown. How the lookup works, String Catalogs and plurals belong to the lesson on strings and locale formatting; here what matters is that the literal and the variable reach different code. ## What Markdown a literal supports The Markdown SwiftUI applies to a key is **inline**: - `**bold**` and `_italic_` (or `*italic*`), - `~~strikethrough~~`, - `` `inline code` ``, drawn in a monospaced face, - `[links](https://example.com)`, which SwiftUI opens through the environment's `openURL` action, so an app can intercept them. Block syntax is not laid out: a literal containing `# Heading` or `- item` shows the hash and the dash as text, and a newline in the literal stays a line break. ## Rendering Markdown that arrives at runtime A push message or a server field is a `String`, so `Text(message)` shows it raw. Two ways to style it: 1. **`AttributedString(markdown:options:)`**, then `Text(attributed)`. The initializer is declared `throws`, so handle the error and fall back to the plain string. With the default `.full` syntax, block elements are parsed into structure that `Text` does not draw, so headings, list items and paragraphs run together on one line; `.init(interpretedSyntax: .inlineOnlyPreservingWhitespace)` keeps the line breaks instead. 2. **`Text(LocalizedStringKey(message))`**. It renders the Markdown, but it also turns server text into a localization key, which is the wrong job for content that was never meant to be translated by the app. `AttributedString` is the honest choice: it says "this is styled content", it can be built once in a model rather than in `body`, and it is the same type you use for styling Markdown cannot express. ## When to choose verbatim `Text(verbatim:)` exists for literals that must never be treated as keys or Markdown: a reference number, a code sample, a symbol such as `**` that is meant to be seen. It also skips the strings lookup, which is useful for debug labels. ## Why the API is shaped this way The split is deliberate rather than an accident of overloads. A literal in source code is text the developer wrote, so SwiftUI treats it as something to translate and lets its author style it with Markdown. A `String` value is data: a merchant name, a note a user typed, a field from a server. SwiftUI displays data exactly as it is, which is also the safe default, because user text containing an underscore or a square bracket should not suddenly turn italic or into a link. That gives a simple test when reading code: - Text the app's authors wrote goes in a literal, and may use inline Markdown. - Text that arrives as data goes in a `String` and is shown as typed. - Data that is meant to carry styling is parsed once into an `AttributedString`, with an explicit decision about which syntax to accept. The same rule explains a surprise in the other direction: a computed property that returns `String` loses the Markdown its literal contained, because by the time `Text` sees it, the value is a `String`. ## Mistakes that come from this - Expecting a model property that holds `"**Pending**"` to render bold. - "Fixing" that by wrapping every server string in `LocalizedStringKey`, which turns content into translation keys. - Passing user-generated text through a Markdown parser so a stray `_` or `[` restyles someone's merchant note. - Putting a heading or a bullet list into one `Text` and expecting block layout; that needs separate views.

  • Why can AttributedString(markdown:) put a heading and its list on one line in a Text?
    With the default `.full` syntax the parser turns blocks into presentation structure on the runs rather than into newline characters, and `Text` draws only the inline styling, so the blocks run together. Parsing with `.inlineOnlyPreservingWhitespace` keeps the source's line breaks; real headings and lists need separate views.
  • How do you intercept a tap on a Markdown link inside a Text?
    Set a custom `OpenURLAction` with `.environment(\.openURL, OpenURLAction { url in … })` on the Text or an ancestor. Apple's documentation says Text views with Markdown links, and links in attributed strings, use that action. The handler returns `.handled`, `.discarded` or `.systemAction` to decide what happens.

  • Text parses Markdown in any String you give it
  • Text(verbatim:) is just a faster spelling of Text(_:) with no other difference
  • A string literal and a String variable reach the same Text initializer
  • Markdown in a Text literal can lay out headings and bullet lists
  • Wrapping server text in LocalizedStringKey is the right way to render its Markdown
open as a page

In SwiftUI, why should a transaction row use font(.headline) or another text style rather than .system(size: 17), and how do custom fonts keep scaling?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A text style such as .headline resolves to a size that follows the user's Dynamic Type setting, while .system(size: 17) stays at 17 points. Custom fonts scale through Font.custom(_:size:), like body or like the style named in relativeTo:.

open as a page

In SwiftUI, how do you show a transaction's amount and date with Text(_:format:) instead of a hand-built string, and what does it handle for you?

level: middleimportance: must knowfreq 65%

basics

~20 s

Text(amount, format: .currency(code: "EUR")) and Text(date, format: .dateTime.day().month()) format the value for the environment's locale when body runs. A relative date formatted this way does not tick; iOS 18 adds Text(.currentDate, format:) styles that update live.

open as a page

In SwiftUI, how do lineLimit, truncationMode, minimumScaleFactor and multilineTextAlignment decide what a long merchant name shows in a transaction row?

level: middleimportance: should knowfreq 55%

basics

~20 s

Text wraps without limit by default. lineLimit caps the lines, as a number or an iOS 16 range; truncationMode places the ellipsis; minimumScaleFactor lets text shrink before truncating; multilineTextAlignment aligns lines only within a multi-line Text.

open as a page

In SwiftUI, how do you put a bold orange "Pending" badge inside one line of Text, and why does Xcode warn about Text + Text?

level: middleimportance: should knowfreq 50%

basics

~20 s

Interpolate a styled Text into a Text literal: Text("(merchant) (badge)"), where badge is Text("Pending").bold().foregroundStyle(.orange). The + operator on Text is deprecated in iOS 26 in favour of this interpolation, which keeps the sentence as one localization key.

open as a page

In a SwiftUI search screen, how do you highlight the matched part of each merchant name with AttributedString when Markdown and Text modifiers cannot express it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Wrap the merchant name in an AttributedString, find the match with range(of:options:), set attributes such as backgroundColor and font on that range, and pass it to Text. Text draws SwiftUI's attributes per run, and a run's attributes win over modifiers.

open as a page