SwiftCSV 0.10.0

SwiftCSV 0.10.0

测试已测试
Lang语言 SwiftSwift
许可证 MIT
发布上次发布2024年5月
SPM支持 SPM

Naoto KanekoLuke StringerChristian Tietze 维护。



SwiftCSV 0.10.0

  • Naoto Kaneko 和 Christian Tietze

SwiftCSV

Swift 5.5 Platform support Build Status Code coverage status CocoaPods Compatible Carthage compatible License MIT

适用于 macOS、iOS、tvOS 和 watchOS 的简单 CSV 解析。

使用方法

可以使用 CSV 类加载 CSV 内容

import SwiftCSV

do {
    // As a string, guessing the delimiter
    let csv: CSV = try CSV(string: "id,name,age\n1,Alice,18")

    // Specifying a custom delimiter
    let tsv: CSV = try CSV(string: "id\tname\tage\n1\tAlice\t18", delimiter: "\t")

    // From a file (propagating error during file loading)
    let csvFile: CSV = try CSV(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(
        name: "users",
        extension: "tsv",
        bundle: .main,
        delimiter: "\t",
        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`.
    ///
    /// - parameter url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
    /// - parameter delimiter: Character used to separate cells from one another in rows.
    /// - parameter encoding: Character encoding to read file (default is `.utf8`)
    /// - parameter 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: Delimiter,
                            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`.
    ///
    /// - parameter url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
    /// - parameter encoding: Character encoding to read file (default is `.utf8`)
    /// - parameter 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)
}

分隔符

分隔符是强类型。认可的 CSV.Delimiter 选项包括: .comma.semicolon.tab

您可以使用便利的初始化器来自动从识别列表中猜测分隔符。这些初始化器适用于从URL和字符串中加载CSV文件。

在加载数据时,您还可以使用任何其他单字符分隔符。使用字符字面量,如"x",将产生CSV.Delimiter.character("x"),因此您不必全部输入.character(_)的情况名称。每个变体都有初始化器,可以接受显式的分隔符设置。

读取数据

// Recognized the comma delimiter automatically:
let csv = CSV(string: "id,name,age\n1,Alice,18\n2,Bob,19")
csv.header         //=> ["id", "name", "age"]
csv.namedRows      //=> [["id": "1", "name": "Alice", "age": "18"], ["id": "2", "name": "Bob", "age": "19"]]
csv.namedColumns   //=> ["id": ["1", "2"], "name": ["Alice", "Bob"], "age": ["18", "19"]]

行也可以即时解析并传递给一个块,从而减少在数组中存储整个数据集所需的内存。

// Access each row as an array (array not guaranteed to 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.init的变体会填充其namedColumnsenumeratedColumns以提供按列访问CSV数据的能力。将其视为一个横截面

let csv = CSV(string: "id,name,age\n1,Alice,18\n2,Bob,19")
csv.namedRows[0]["name"]  //=> "Alice"
csv.namedColumns["name"]  //=> ["Alice", "Bob"]

如果您只想按行访问数据,而不是按列,则可以将任何初始化器中的loadColumns参数设置为false。这将防止填充列数据。

跳过此步骤可以提高大量数据的性能。

安装

CocoaPods

pod "SwiftCSV"

Carthage

github "swiftcsv/SwiftCSV"

SwiftPM

.package(url: "https://github.com/swiftcsv/SwiftCSV.git", from: "0.6.1")