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.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35