๐Ÿ”ฐMarkdown

In WWDC 2021 Apple announced to add Markdown support to the Foundation (AttributedString) and SwiftUI (Text) starting with iOS 15.

// โญ๏ธ Markdown works with string literals
Text("~~strikethrough~~")
Text("**bold**\n*italic*")    // line breaks OK

// โญ๏ธ Markdown doesn't work with string variables/interpolations
let markdown = "**Doesn't** *Work* with string variables/interpolations."
Text(markdown).foregroundColor(.pink)
Text(verbatim: markdown)
Text("\(markdown)")
Text(verbatim: "\(markdown)")

// ------------------------
//     AttributedString
// ------------------------

// โญ๏ธ AttributedString supports string variables
let str = "`AttributedString` **DOES** support *string variables*"
let attrStrSupportStrVar = try! AttributedString(markdown: str)

// โญ๏ธ AttributedString ignores line breaks by default.
let lineBreaksIgnored = try! AttributedString(
    markdown: "**No**\n~~*Line*~~\n`Breaks`!"
)
// โญ๏ธ add option to support line breaks.
let respectLineBreaks = try! AttributedString(
    markdown: "**Line 1**\n~~*Line 2*~~\n!", 
    options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
)

Text(attrStrSupportStrVar).foregroundColor(.green)
Text(lineBreaksIgnored).foregroundColor(.pink)
Text(respectLineBreaks)
    .multilineTextAlignment(.center)
    .foregroundColor(.blue)

Last updated