A small project to convert a CSV Document into a model :)
- Create a model which implements the
Codable
protocol.
struct Ingredient: Codable {
var name_ger: String
var kcal: Double
var kcal_unit: String
}
- Your CSV-file could look like this.
ID | name D | energy kcal | energy unit |
---|---|---|---|
381 | Banane, roh | 95 | kilocalorie |
Now you create an array with the attribtues you want to read. Each element represents a column in your CSV-file. Columns you do not want to read you can insert a nil
.
let attributesToReadFromTable = [nil, "name_ger", "kcal", "kcal_unit"]
- Initialize and adjust the CSVReader.
let csvReader = CSVReader<Ingredient>(csvString: csvString, attributeNames: attributesToReadFromTable)
csvReader.decimalSeparator = ","
csvReader.elementSeparator = ";"
- Implement the CSVReaderDelegate to track the proccess (if needed).
extension ViewController: CSVReaderDelegate {
func changed(progress: Float) {
progressView.progress = progress
}
}
- Call the
.read()
method.
let result = csvReader.read()
Thank you for the free data - www.naehrwertdaten.ch