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:
“See the “, with no attributes.“latest”, with an AttributeScopes.FoundationAttributes.InlinePresentationIntentAttribute whose value is emphasized.“ news at “, with no attributes.“our website”, with an AttributeScopes.FoundationAttributes.LinkAttribute whose value is a URL.“.”, with no attributes.
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
init(markdown:options:baseURL:)init(markdown:including:options:baseURL:)init(markdown:including:options:baseURL:)
Initializing from Markdown Data
init(markdown:options:baseURL:)init(markdown:including:options:baseURL:)init(markdown:including:options:baseURL:)
Initializing with Markdown from URL Contents
init(contentsOf:options:baseURL:)init(contentsOf:including:options:baseURL:)init(contentsOf:including:options:baseURL:)