read and write CSV files in Swift 3

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

I've seen different libraries like SwiftCSV, CSwiftV. AFAIK, they made for previous versions of swift. I need a very simple realization for swift 3 : open file, read line, put into array; or open, write array to csv file, and that's it. Any help?

I have:

struct Data {     var DataTime: Date = Date()     var Price: Double = 0.0 }  func DatafromCSV(_ CSV: String, _ separator: String) -> [Data] {     var x = [Data]()      //open file, read line, put into array, close file      return x }  func DatatoCSV(_ CSV: String, _ separator: String) -> [Data] {     var x = [Data]()      //create file (erase data if exists, write data from array, close file      return x } 

回答1:

Try to use CSVImporter Framework, is very simple. You can add it to your projects following this link: https://github.com/Flinesoft/CSVImporter

static func extractFromCSV(){        //the Path of the csv        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!        let destinationFileUrl = documentsUrl.appendingPathComponent("name.csv")        let path = destinationFileUrl.path        let importer = CSVImporter<YourClassName?>(path: path,delimiter: ";")        importer.importRecords{ recordValues -> Sede_Azienda? in          //this piece of code is called for each row. You can access to each field with recordValues[x] and manage the data.          return nil //or the object if you need it        }  } 

This is asynchronous but this framework has also some sync methods. Look the documentation.

NB: YourClassName is the type of class of the returned object if you need it.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!