CSVParser
安装
克隆仓库,打开项目,然后运行。运行成功后,导航到 'Products' 文件夹,将框架拖动到您的项目目录。
import LDCSVParser
解析器
使用字符串创建解析器的实例
let csv = "id,name,age\n1,Alice,18\n2,Bob,19\n3,Charlie,20"
let parser = CSVParser(with: csv)
使用字符串和自定义标题创建解析器的实例
let csv = "id,name,age\n1,Alice,18\n2,Bob,19\n3,Charlie,20"
parser = CSVParser(with: csv, headers: headers)
使用字符串、自定义分隔符和自定义头创建解析器实例
let csv = "id,name,age\n1,Alice,18\n2,Bob,19\n3,Charlie,20"
parser = CSVParser(with: csv, separator: separator, headers: header)
有用的属性
parser.headers // The headers from the data, an Array of String
parser.keyedRows // An array of Dictionaries with the values of each row keyed to the header
parser.rows // An Array of Arrays of the values
对象创建
从csv数据中创建对象很简单。解析器有方法可以直接从键行创建单独的对象。
注意:.build方法是通用的,因此必须提供一个符合Codeable的类作为完成处理程序的参数。
考虑以下类
class Person: Codable {
let name: String
let age: String
let id: String
}
class SomeViewController {
func someMethond() {
if let keyed = parser.keyedRows {
// build an object with the keyed rows using the Person class
parser.build(with: keyed) { (people: [Person]) in
for person in people {
print(person.name)
}
}
}
}
}