警告
此仓库已被归档。
如果您需要使用 Swift 解析和转换 Markdown,请考虑使用 https://github.com/apple/swift-markdown;如果您需要在 SwiftUI 中渲染 Markdown,请考虑使用 https://github.com/gonzalezreal/swift-markdown-ui。
SwiftCommonMark 是一个用于在 Swift 中解析和创建 Markdown 文档的库,完全符合 CommonMark 规范。
一个 CommonMark Document
由一系列块(blocks)组成,这些块是结构性元素,例如段落、块引用、列表、标题、规则和代码块。 一些块,例如块引用和列表项,包含其他块; 另一些块,例如标题和段落,包含内联文本、链接、强调文本、图像、代码片段等。
您可以通过将 CommonMark 格式的 String
或 Data
实例传递给初始化程序(例如 init(markdown:options:)
)来创建一个 Document
。
do {
let document = try Document(
markdown: "You can try **CommonMark** [here](https://spec.commonmark.org/dingus/)."
)
} catch {
print("Couldn't parse document.")
}
从 Swift 5.4 开始,您可以通过传递一个使用 BlockArrayBuilder
构建的 Block
数组来创建一个 Document
。
let document = Document {
Heading(level: 2) {
"Markdown lists"
}
Paragraph {
"Sometimes you want numbered lists:"
}
OrderedList {
"One"
"Two"
"Three"
}
Paragraph {
"Sometimes you want bullet points:"
}
BulletList {
ListItem {
Paragraph {
"Start a line with a "
Strong("star")
}
}
ListItem {
"Profit!"
}
ListItem {
"And you can have sub points:"
BulletList {
"Like this"
"And this"
}
}
}
}
您可以通过访问 Document
的 blocks
属性来检查 Document
的元素。
for block in document.blocks {
switch block {
case .blockQuote(let blockQuote):
for item in blockQuote.items {
// Inspect the item
}
case .bulletList(let bulletList):
for item in bulletList.items {
// Inspect the list item
}
case .orderedList(let orderedList):
for item in orderedList.items {
// Inspect the list item
}
case .code(let codeBlock):
print(codeBlock.language)
print(codeBlock.code)
case .html(let htmlBlock):
print(htmlBlock.html)
case .paragraph(let paragraph):
for inline in paragraph.text {
// Inspect the inline
}
case .heading(let heading):
print(heading.level)
for inline in heading.text {
// Inspect the inline
}
case .thematicBreak:
// A thematic break
}
}
您可以获取 Document
的 CommonMark 格式文本,或者将其渲染为 HTML。
let markdown = document.renderCommonMark()
let html = document.renderHTML()
您可以通过将 SwiftCommonMark 添加为包依赖项来将其添加到 Xcode 项目中。
https://github.com/gonzalezreal/SwiftCommonMark