Quick Tip Icon
Quick Tip

Markdown in SwiftUI Text views

Since iOS 15 and macOS 12 SwiftUI Text views will parse Markdown by default when created with a LocalizedStringKey. When we create Text with a string literal, the initializer that is actually called is the one that accepts a LocalizedStringKey: init(_:tableName:bundle:comment:).

// Markdown will be parsed by Text view.
Text("Markdown string with *emphasized* text.")

Markdown will not be parsed by default and text will not be localized if it’s created from a string variable.

struct ContentView: View {
    let str = "Markdown string with *emphasized* text."
    
    var body: some View {
        // Markdown won't be parsed by Text view.
        Text(str)
    }
}

Markdown also won't be parsed when we create a Text view using init(verbatim:).

// Markdown won't be parsed by Text view.
Text(verbatim: "Markdown string with *emphasized* text.")

If you'd like to parse Markdown but don't need to localize the text, then you can first create an AttributedString and then pass it to a Text view.

struct ContentView: View {
    // Force unwrap because we have a valid Markdown string.
    let attributedString = try! AttributedString(
        markdown: "Markdown string with *emphasized* text.")
    
    var body: some View {
        Text(attributedString)
    }
}

Note that Markdown is parsed slightly differently by AttributedString and by Text. When it's localized, like in the case with LocalizedStringKey inside Text view, it implicitly uses inlineOnlyPreservingWhitespace parsing option.