In SwiftUI, why does Text render **Pending** in bold from a string literal but show the asterisks when it comes from a String variable?
answer
- which initializer the compiler picks
- literal becomes a LocalizedStringKey
- init(verbatim:) and init(_:) for String
- AttributedString(markdown:) at runtime
basics
~20 sA 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 linesimport 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
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.
Explain why overload resolution picks different initializers for a literal and a String, and show AttributedString(markdown:options:) with a fallback when parsing throws.
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.
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