我见过不同的库,例如 SwiftCSV、CSwiftV。 AFAIK,他们是为 swift 的早期版本制作的。我需要 swift 3 的一个非常简单的实现:打开文件,读取行,放入数组;或者打开,将数组写入 csv 文件,就是这样。有什么帮助吗?
我有:
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
}
最佳答案
尝试使用CSVImporter Framework,很简单。您可以通过以下链接将其添加到您的项目中: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
}
}
这是异步的,但这个框架也有一些同步方法。查看文档。
注意:如果您需要,YourClassName 是返回对象的类类型。
关于swift - 在 Swift 3 中读写 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104362/