Skip to content

Instantly share code, notes, and snippets.

@michaelrockhold
Created February 15, 2019 18:03
Show Gist options
  • Save michaelrockhold/3e7f72a1db3330dd3b03181c4fa4f9f5 to your computer and use it in GitHub Desktop.
Save michaelrockhold/3e7f72a1db3330dd3b03181c4fa4f9f5 to your computer and use it in GitHub Desktop.
Very simple CSV reader in Swift; probably not suitable for very large files
//
// CSVReader.swift
//
// Created by Michael Rockhold on 2/15/19.
// Copyright © 2019 Michael Rockhold. All rights reserved.
//
import Foundation
struct CSVReader: Sequence {
func makeIterator() -> CSVReaderIterator {
return CSVReaderIterator(self)
}
struct CSVReaderIterator: IteratorProtocol {
var csvReader: CSVReader
init(_ r:CSVReader) {
csvReader = r
}
mutating func next() -> [String]? {
repeat {
if let row = csvReader.rowIterator.next() {
let tuple = row.split(separator: ",", maxSplits: 32, omittingEmptySubsequences: false).map { String($0) }
if !(tuple.count == 1 && tuple[0] == "") {
return tuple
}
} else {
return nil
}
} while true
}
}
let data: String
var rowIterator: IndexingIterator<[String.SubSequence]>
init?(filename:String) {
do {
data = try String(contentsOfFile: filename)
let rows = data.split(separator: "\n", omittingEmptySubsequences: false)
rowIterator = rows.makeIterator()
} catch {
return nil
}
}
}
@michaelrockhold
Copy link
Author

You might call this with something like:

let data50 = "data/data50.csv"

for row in CSVReader(filename: data50)! {
    let (articleId, wordId, count) = (row[0],row[1],row[2])
    print(articleId, wordId, count)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment