Swift Markdown の使い方
Swiftで書かれたMarkdownパーサーをGitHub検索したら、Apple謹製のものがあった。
最新リリースは2時間前、ということでメンテもされている。2.6kスターということである程度枯れてもいそう。良さそうなのでこれを使ってみたメモ。
導入
Xcodeから [Add Package Dependencies] で追加するだけ
最小実装
パッケージ名はシンプルに `Markdown`
import Markdown
`Document` 構造体のイニシャライザにmarkdownテキストの文字列を渡すだけ。
let document = Document(parsing: markdownStr)
print(document.debugDescription())
こんな感じの出力が得られる:
Document
└─ Paragraph
├─ Text "This is a markup "
├─ Emphasis
│ └─ Text "document"
└─ Text "."
Markdownのパース
`Document` は `Markup` プロトコルに準拠している
struct Document: Markup, BasicBlockContainer
この機能を通じてパースしていくことになるので、やりたいことに応じて適宜ここのヘッダを見ればいい。
WWDC の Transcript をパースしてみる
こういう感じのマークダウンをパースしたい
[♪ Bass music playing ♪ ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=2)[♪ ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=7)[Brad Ford: Hello and welcome to "What's new in camera capture." ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=9)[I'm Brad Ford from the Camera Software team. ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=13)[I'll be presenting a host of new camera features ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=16)[beginning with minimum focus distance reporting; ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=18)[how to capture 10-bit HDR video; ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=22)…
[Here's a sample app called AVCamBarcode. ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=222)[It showcases our AVFoundation barcode detection APIs. ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=225)[The UI guides the user to position an object ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=228)[inside of a rectangle for scanning. ](https://developer.apple.com/videos/play/wwdc2021/10047/?time=231)…
…
Markdownの特徴としては、
ひたすらリンク付きテキストが並ぶ
たまにパラグラフを分ける改行あり
で、これを、
パラグラフごとに分けて
テキストと、タイムスタンプを抽出したい
つまりこんな感じの構造体にパースしたい
struct Transcript {
struct TimestampedText {
let text: String
let timestamp: TimeInterval
}
struct Paragraph {
let texts: [TimestampedText]
}
let paragraphs: [Paragraph]
}
最後まで読んでいただきありがとうございます!もし参考になる部分があれば、スキを押していただけると励みになります。 Twitterもフォローしていただけたら嬉しいです。 https://twitter.com/shu223/