CSV 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
- ✓CSV Parser runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Foundation has no CSV parser. On Apple platforms the first-party answer is the TabularData framework: DataFrame(contentsOfCSVFile: url, options: CSVReadingOptions(hasHeaderRow: true, delimiter: ",")) parses and infers column types, but it exists only on Apple platforms, not on Linux.
- ✓Reviewers want the scan done over the utf8 view or raw bytes and String produced only at the boundary.
- ✓The Swift trap: Character is an extended grapheme cluster, and CRLF is ONE Character in Swift. A scanner written over a String's Character view therefore never observes a lone newline in a Windows export, and a comparison against "\n" quietly fails on every row of the file.
- ✓Every field you materialise is a String carrying ARC retain and release traffic; strings up to fifteen UTF-8 bytes live inline in the small-string form and allocate nothing, longer ones hit the heap, so wide text columns are where the cost concentrates.
What CSV Parser actually is
CSV Parser in Swift: what you actually reach for
Swift implementation
import Foundation
// Byte-level on purpose: Swift treats CRLF as ONE Character, and String
// indices are not integers, so a Character scanner is both wrong and O(n^2).
func parseCSV(_ data: Data, delimiter: UInt8 = 0x2C) -> [[String]] {
var bytes = [UInt8](data)
if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { bytes.removeFirst(3) } // BOM
var rows: [[String]] = [], row: [String] = [], field: [UInt8] = []
var quoted = false, pending = false, i = 0
rows.reserveCapacity(1024)
func endField() {
row.append(String(decoding: field, as: UTF8.self))
field.removeAll(keepingCapacity: true)
}
while i < bytes.count {
let b = bytes[i]
if quoted {
if b == 0x22 {
if i + 1 < bytes.count, bytes[i + 1] == 0x22 {
field.append(0x22); i += 2; continue // "" escape
}
quoted = false; i += 1; continue
}
field.append(b); i += 1; continue // delimiter and CR/LF are data
}
switch b {
case 0x22: quoted = true; pending = true
case delimiter: endField(); pending = true
case 0x0D, 0x0A:
if b == 0x0D, i + 1 < bytes.count, bytes[i + 1] == 0x0A { i += 1 }
endField(); rows.append(row); row.removeAll(keepingCapacity: true)
pending = false
default: field.append(b); pending = true
}
i += 1
}
if pending { endField(); rows.append(row) } // no phantom row after LF
return rows
}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 CSV Parser?
Foundation has no CSV parser. On Apple platforms the first-party answer is the TabularData framework: DataFrame(contentsOfCSVFile: url, options: CSVReadingOptions(hasHeaderRow: true, delimiter: ",")) parses and infers column types, but it exists only on Apple platforms, not on Linux. Cross-platform code reaches for CodableCSV (CSVReader, CSVDecoder) or SwiftCSV. Hand-rolled parsers read Data and walk UInt8, materialising fields with String(decoding: bytes, as: UTF8.self); note that String.Encoding.utf8 does not remove a BOM for you.
What is the most common Swift mistake when implementing CSV Parser?
Character is an extended grapheme cluster, and CRLF is ONE Character in Swift. A scanner written over a String's Character view therefore never observes a lone newline in a Windows export, and a comparison against "\n" quietly fails on every row of the file. The same view makes position arithmetic O(n): calling s.index(s.startIndex, offsetBy: i) inside the loop turns the parser quadratic, because String indices are not integers. Work in string.utf8 or [UInt8]. Separately, String(data:encoding:.utf8) preserves a leading U+FEFF, so the first header key is not what you typed.
How does CSV Parser actually perform in Swift?
Every field you materialise is a String carrying ARC retain and release traffic; strings up to fifteen UTF-8 bytes live inline in the small-string form and allocate nothing, longer ones hit the heap, so wide text columns are where the cost concentrates. Arrays are copy-on-write, so handing rows to a closure that mutates them forces a full copy; reserveCapacity and append in place. Scanning [UInt8] under withUnsafeBufferPointer removes bounds checks and retain traffic; Data subscripting is not free because Data can be discontiguous. 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 trialStudying for this? Replit free tiers and academic plans are laid out 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.