Created
February 15, 2019 18:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You might call this with something like: