swift - 在 Swift 3 中读写 CSV 文件

标签 swift csv

我见过不同的库,例如 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/

相关文章:

ios - 如何更改绘图线的粗细?

java - 如果文件已包含数据,则将数据添加到新行 - Java

c - C 中文件读取的奇怪行为

ios - 如何在警报 View 中的文本之间添加图像?

swift - Firebase Swift 查询符号

ios - Firebase 插入具有 2 个关键属性的数据

mysql - LOAD DATA LOCAL INFILE 给出错误 The used command is not allowed with this MySQL version

python - 选择正确的 csv 文件

powershell - 在Powershell中将列表/数组导出为CSV

ios - 在 UITextField swift 3.0 中使用数字键盘以 dd-MM-yyyy 格式输入日期