NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
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

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift