Skip to content

Instantly share code, notes, and snippets.

@younata
Created October 7, 2018 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save younata/c2ca89f037eeade4d54e0c12c01221b7 to your computer and use it in GitHub Desktop.
Save younata/c2ca89f037eeade4d54e0c12c01221b7 to your computer and use it in GitHub Desktop.
Bad CSV Parser in swift
// Quick and dirty CSV parser I wrote. Handles edge cases badly. Doesn't perform well. Doesn't handle large csv files.
// But, hey, it solved my use case!
// Swift 4.2+
func parseCSVBadly(csvData: Data) -> [[String]] {
guard let csv = String(data: csvData, encoding: .utf8) else { return [] }
return csv.components(separatedBy: CharacterSet.newlines).compactMap { line in
guard !line.hasPrefix("#") else { return nil }
return line.components(separatedBy: ",")
}
}
import Quick
import Nimble
final class CSVParserSpec: QuickSpec {
override func spec() {
it("Parses csvs") {
let data = "a,b,c,d\ne,f".data(using: .utf8)!
expect(
parseCSVBadly(csvData: data)
).to(equal([["a", "b", "c", "d"], ["e", "f"]]))
}
it("ignores lines prefixed with '#'s") {
let data = """
a,b,c,d
# whatever.
e,f,g
""".data(using: .utf8)!
expect(
parseCSVBadly(csvData: data)
).to(equal([["a", "b", "c", "d"], ["e", "f", "g"]]))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment