macOS、iOS、tvOS 和 watchOS 平台的简易 CSV 解析库。
可以使用 CSV
类加载 CSV 内容
import SwiftCSV
do {
// As a string, guessing the delimiter
let csv: CSV = try CSV<Named>(string: "id,name,age\n1,Alice,18")
// Specifying a custom delimiter
let tsv: CSV = try CSV<Enumerated>(string: "id\tname\tage\n1\tAlice\t18", delimiter: .tab)
// From a file (propagating error during file loading)
let csvFile: CSV = try CSV<Named>(url: URL(fileURLWithPath: "path/to/users.csv"))
// From a file inside the app bundle, with a custom delimiter, errors, and custom encoding.
// Note the result is an optional.
let resource: CSV? = try CSV<Named>(
name: "users",
extension: "tsv",
bundle: .main,
delimiter: .character("🐠"), // Any character works!
encoding: .utf8)
} catch parseError as CSVParseError {
// Catch errors from parsing invalid CSV
} catch {
// Catch errors from trying to load files
}
CSV
类自带初始化器,适用于从 URL 加载文件。
extension CSV {
/// Load a CSV file from `url`.
///
/// - Parameters:
/// - url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
/// - delimiter: Character used to separate separate cells from one another in rows.
/// - encoding: Character encoding to read file (default is `.utf8`)
/// - loadColumns: Whether to populate the columns dictionary (default is `true`)
/// - Throws: `CSVParseError` when parsing the contents of `url` fails, or file loading errors.
public convenience init(url: URL,
delimiter: CSVDelimiter,
encoding: String.Encoding = .utf8,
loadColumns: Bool = true) throws
/// Load a CSV file from `url` and guess its delimiter from `CSV.recognizedDelimiters`, falling back to `.comma`.
///
/// - Parameters:
/// - url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
/// - encoding: Character encoding to read file (default is `.utf8`)
/// - loadColumns: Whether to populate the columns dictionary (default is `true`)
/// - Throws: `CSVParseError` when parsing the contents of `url` fails, or file loading errors.
public convenience init(url: URL,
encoding: String.Encoding = .utf8,
loadColumns: Bool = true)
}
分隔符是强类型的。可识别的 CSVDelimiter
枚举值包括:.comma
(逗号)、.semicolon
(分号)和 .tab
(制表符)。
您可以使用便捷初始化器,从识别列表中猜测分隔符。这些初始化器可用于从 URL 和字符串加载 CSV。
加载 CSV 数据时,您也可以使用任何其他单字符分隔符。像 "x"
这样的字符字面量将生成 CSV.Delimiter.character("x")
,因此您不必键入完整的 .character(_)
枚举值名称。每个变体都有接受显式分隔符设置的初始化器。
// Recognized the comma delimiter automatically:
let csv = CSV<Named>(string: "id,name,age\n1,Alice,18\n2,Bob,19")
csv.header //=> ["id", "name", "age"]
csv.rows //=> [["id": "1", "name": "Alice", "age": "18"], ["id": "2", "name": "Bob", "age": "19"]]
csv.columns //=> ["id": ["1", "2"], "name": ["Alice", "Bob"], "age": ["18", "19"]]
行也可以被解析并动态传递给一个代码块,从而减少存储整个数组所需的内存
// Access each row as an array (inner array not guaranteed to always be equal length to the header)
csv.enumerateAsArray { array in
print(array.first)
}
// Access them as a dictionary
csv.enumerateAsDict { dict in
print(dict["name"])
}
使用 CSV<Named>
,也称为 NamedCSV
,以按列方式访问 CSV 数据,并使用命名列。可以将其视为横截面
let csv = NamedCSV(string: "id,name,age\n1,Alice,18\n2,Bob,19")
csv.rows[0]["name"] //=> "Alice"
csv.columns["name"] //=> ["Alice", "Bob"]
如果您只想逐行访问数据,而不是按列访问,则可以使用 CSV<Enumerated>
或 EnumeratedCSV
let csv = EnumeratedCSV(string: "id,name,age\n1,Alice,18\n2,Bob,19")
csv.rows[0][1] //=> "Alice"
csv.columns?[0].header //=> "name"
csv.columns?[0].rows //=> ["Alice", "Bob"]
为了加速,通过传递 loadColumns: false
完全跳过填充按列访问。这将阻止填充列式数据。对于大型数据集,这可以节省大量迭代(在二次运行时)。
let csv = EnumeratedCSV(string: "id,name,age\n1,Alice,18\n2,Bob,19", loadColumns: false)
csv.rows[0][1] //=> "Alice"
csv.columns //=> nil
pod "SwiftCSV"
github "swiftcsv/SwiftCSV"
.package(url: "https://github.com/swiftcsv/SwiftCSV.git", from: "0.8.0")
该软件包附带一个空的隐私清单,因为它不访问或跟踪任何敏感数据。