Markdown with AttributedString in SwiftUI

SwiftUI 3.0 comes with amazing new features, including markdown support with AttributedString. Let's see how to format a string from markdown using AttributedStrings!

Use AttributedString to generate formatted text from markdown.


AttributedString is only supported in applications running on iOS 15.0 and higher. You'll need Xcode 13 and need to set your Xcode project's iOS target version to iOS 15.0 or higher, or wrap the code presented in this section in an if #available(iOS 15.0, *).

Create markdown

First, we'll need to create our markdown text as a String. Please note that AttributedStrings do not support code blocks yet. 

Only links, short code, bold and italic text is supported for now.

let markdown = "Visit [SwiftUIIO]( to learn how to `code` and  design Swift UI."


Create the AttributedString 

In your view, create an AttributedString state where we'll save the created AttributedString. We'll set it to an empty String by default.

@State private var myString: AttributedString = ""


Create the AttributedString from markdown. It might throw an error, so remember to add a try in front of the AttributedString and wrap everything in a do catch statement.

do {
    myString = try AttributedString(markdown: markdown)
} catch {
    print("Error creating AttributedString:  \(error)")


Display the AttributedString 

Text also supports AttributedStrings now, so we can simply pass our myString variable to a Text.



Now try this in the Simulator..