Markdown Parser Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Markdown Parser runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Foundation already does this. AttributedString(markdown:) parses a documented CommonMark subset into runs carrying inlinePresentationIntent and presentationIntent attributes, and it throws on malformed input rather than degrading.
- ✓Choose the view deliberately. A block scanner runs over document.unicodeScalars holding String.Index values, never Int offsets, because String has no integer subscript and manufacturing one costs a linear walk.
- ✓The Swift trap: A carriage return and line feed are one Character. String is a collection of grapheme clusters and Unicode text segmentation binds CRLF into a single element, so "\r\n".count is 1 while its unicodeScalars.count is 2.
- ✓Substring shares the parent's storage, which is a memory decision more than a speed one: one Substring per text node pins the entire source buffer until the last node dies, so long-lived nodes should call String(sub) and pay the copy deliberately.
What Markdown Parser actually is
Markdown Parser in Swift: what you actually reach for
Swift implementation
import Foundation
// Swift folds CRLF into a single Character, so line splitting for a block
// scanner runs over the unicode scalar view, never over Characters.
func markdownLines(of document: String) -> [Substring] {
var out: [Substring] = []
let scalars = document.unicodeScalars
var start = scalars.startIndex
var i = start
while i < scalars.endIndex {
let s = scalars[i]
if s == "\n" || s == "\r" {
out.append(document[start..<i])
var next = scalars.index(after: i)
if s == "\r", next < scalars.endIndex, scalars[next] == "\n" {
next = scalars.index(after: next) // one line ending, not two
}
i = next
start = i
} else {
i = scalars.index(after: i)
}
}
if start < scalars.endIndex { out.append(document[start...]) }
return out
}
let doc = "# Spring tides\r\n\r\nHigh water *at* 04:12.\r\n"
for line in markdownLines(of: doc) {
print(line.count, "|", line)
}
// prints 39 and 42: three CRLF endings, three Characters, six scalars
print("characters:", doc.count, "scalars:", doc.unicodeScalars.count)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Markdown Parser?
Foundation already does this. AttributedString(markdown:) parses a documented CommonMark subset into runs carrying inlinePresentationIntent and presentationIntent attributes, and it throws on malformed input rather than degrading. Apple's swift-markdown package goes considerably further, wrapping cmark-gfm behind Document(parsing:) with Strong, Emphasis and Link node types and MarkupWalker or MarkupVisitor for traversal; DocC is built on it. Writing the scanner yourself, the pieces are String.UnicodeScalarView, Unicode.Scalar.Properties.generalCategory returning cases such as finalPunctuation, and Substring for slices that copy nothing.
What is the most common Swift mistake when implementing Markdown Parser?
A carriage return and line feed are one Character. String is a collection of grapheme clusters and Unicode text segmentation binds CRLF into a single element, so "\r\n".count is 1 while its unicodeScalars.count is 2. Any scanner that walks Characters and derives column positions from them drifts by one per Windows line ending: the three-line document in the snippet below measures 39 characters against 42 scalars. Canonical equivalence compounds it, because "e\u{301}" == "é" is true, so two sources that differ byte for byte compare equal at Character level and offsets computed from either disagree.
How does Markdown Parser actually perform in Swift?
Substring shares the parent's storage, which is a memory decision more than a speed one: one Substring per text node pins the entire source buffer until the last node dies, so long-lived nodes should call String(sub) and pay the copy deliberately. Copy-on-write makes passing arrays of nodes free until something mutates. Each case of an indirect enum is its own heap box, so a deep inline tree is one allocation per node. Reserve capacity on the output buffer, and stay in unicodeScalars to skip grapheme breaking on every character. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.