Instantiating Attributed Strings with Markdown Syntax

Use a Markdown-syntax string to iniitalize an attributed string with standard or custom attributes.

Overview 概要

You can use familiar Markdown syntax to initialize an attributed string with both its initial text and attributes for things like inline styles and links. In many cases, this produces easier-to-read code than manually setting attributes on ranges of an existing attributed string.


if let attString = try? AttributedString(
    markdown: "See the *latest* news at [our website](https://example.com)."),
    let websiteRange = attString.range(of: "our website"),
    let link = attString[websiteRange].link {
    print("\(link)") // Prints "https://example.com".
}

In this example, attString contains five runs, with attributes parsed from the syntax in the markdown parameter:

You can also use custom attributes defined with the MarkdownDecodableAttributedStringKey protocol in the Markdown string. To do this, use Apple’s Markdown extension syntax: ^[text](attribute1: value1, attribute2: value2, …).

When using attributes beyond those provided by the system, be sure to use initializers that take a scope parameter, and provide the scope that defines the custom attributes.

Topics 話題

Initializing from Markdown Strings

Initializing from Markdown Data

Initializing with Markdown from URL Contents

Specifying Markdown Parsing Options