Swiftpack.co - Package - yaslab/CSV.swift

CSV.swift

Build Status codecov Open Source Helpers

CSV reading and writing library written in Swift.

Usage for reading CSV

From string

import CSV

let csvString = "1,foo\n2,bar"
let csv = try! CSVReader(string: csvString)
while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]

From file

NOTE: The default character encoding is UTF8.

import Foundation
import CSV

let stream = InputStream(fileAtPath: "/path/to/file.csv")!
let csv = try! CSVReader(stream: stream)
while let row = csv.next() {
    print("\(row)")
}

Getting the header row

import CSV

let csvString = "id,name\n1,foo\n2,bar"
let csv = try! CSVReader(string: csvString,
                         hasHeaderRow: true) // It must be true.

let headerRow = csv.headerRow!
print("\(headerRow)") // => ["id", "name"]

while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]

Get the field value using subscript

import CSV

let csvString = "id,name\n1,foo"
let csv = try! CSVReader(string: csvString,
                         hasHeaderRow: true) // It must be true.

while csv.next() != nil {
    print("\(csv["id"]!)")   // => "1"
    print("\(csv["name"]!)") // => "foo"
}

Provide the character encoding

If you use a file path, you can provide the character encoding to initializer.

import Foundation
import CSV

let stream = InputStream(fileAtPath: "/path/to/file.csv")!
let csv = try! CSVReader(stream: stream,
                         codecType: UTF16.self,
                         endian: .big)

Reading a row into a Decodable object

If you have a destination object that conforms to the Decodable protocol, you can serialize a row with a new instances of the object.

struct DecodableExample: Decodable {
    let intKey: Int
    let stringKey: String
    let optionalStringKey: String?
}

let csv = """
    intKey,stringKey,optionalStringKey
    1234,abcd,
    """

var records = [DecodableExample](https://raw.github.com/yaslab/CSV.swift/blob/master/)
do {
    let reader = try CSVReader(string: csv, hasHeaderRow: true)
    let decoder = CSVRowDecoder()
    while reader.next() != nil {
        let row = try decoder.decode(DecodableExample.self, from: reader)
        records.append(row)
    }
} catch {
    // Invalid row format
}

Usage for writing CSV

Write to memory and get a CSV String

NOTE: The default character encoding is UTF8.

import Foundation
import CSV

let csv = try! CSVWriter(stream: .toMemory())

// Write a row
try! csv.write(row: ["id", "name"])

// Write fields separately
csv.beginNewRow()
try! csv.write(field: "1")
try! csv.write(field: "foo")
csv.beginNewRow()
try! csv.write(field: "2")
try! csv.write(field: "bar")

csv.stream.close()

// Get a String
let csvData = csv.stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data
let csvString = String(data: csvData, encoding: .utf8)!
print(csvString)
// => "id,name\n1,foo\n2,bar"

Write to file

NOTE: The default character encoding is UTF8.

import Foundation
import CSV

let stream = OutputStream(toFileAtPath: "/path/to/file.csv", append: false)!
let csv = try! CSVWriter(stream: stream)

try! csv.write(row: ["id", "name"])
try! csv.write(row: ["1", "foo"])
try! csv.write(row: ["1", "bar"])

csv.stream.close()

Installation

CocoaPods

pod 'CSV.swift', '~> 2.4.3'

Carthage

github "yaslab/CSV.swift" ~> 2.4.3

Swift Package Manager

.package(url: "https://github.com/yaslab/CSV.swift.git", .upToNextMinor(from: "2.4.3"))

Reference specification

License

CSV.swift is released under the MIT license. See the LICENSE file for more info.

Github

link
Stars: 453

Dependencies

Releases

2.4.2 - 2019-07-13 07:14:21

This release targets Swift 5.0.x / Xcode 10.2.x.

Fixed

  • Fix a crash that occurs when the number of fields is small (#92). Thanks a72 for reporting this issue!
  • Fix CSV Deprecated compiler warning (#93). Thanks robwithhair for reporting this issue!

Breaking change

In 2.4.2 and later versions, If you specify a key that does not have a value in subscript, an empty string is returned. For example,

let csvString = "key1,key2\nvalue1" // There is only one field in the second line.
let csv = try! CSVReader(string: csvString, hasHeaderRow: true)
csv.next()
let value2 = csv["key2"] // Change point: Formerly nil, now "" is returned.
let value3 = csv["key3"] // In this case, nil will be returned.

2.4.1 - 2019-06-22 12:28:00

This release targets Swift 5.0.x / Xcode 10.2.x.

Fixed

  • CSVWriter: Automatically quote values that contain commas (#89). Thanks mxcl for the pull request!

2.4.0 - 2019-05-11 03:02:23

This release targets Swift 5.0.x / Xcode 10.2.x (#84). Thanks UberJason for the pull request!

2.3.0 - 2018-12-01 04:27:10

This release targets Swift 4.2.1 / Xcode 10.1.

Added

  • Decodable support (#61). Please see README.md for usage. Thanks yoiang for the pull request!
  • Added support for decoding with Int-based CodingKey (#72). Thanks sstadelman for the pull request!

Improved

  • Improved reading speed when using InputStream. (#65)

- 2017-09-23 09:46:27

Fixed

  • Xcode 9 (Swift 3.2 / Swift 4.0) compatibility (#37, #38). Thanks pefaymon for the pull request!

- 2017-07-09 06:18:51

Document updates only.

- 2017-07-09 06:01:57

This release targets Swift 3.1 / Xcode 8.3.

Added

  • Add the CSVWriter class (#22). Please see README.md for usage. Thanks kgn for the proposal!

- 2016-11-29 13:14:40

This release targets Swift 3.0.1 / Xcode 8.1.

Fixed

  • Add support for Linux-based builds (#18). Thanks choefele for the pull request!

- 2016-11-15 17:05:03

This release targets Swift 3.0.1 / Xcode 8.1.

Fixed

  • Updates PackageManager structure to fix error (#17). Thanks lightsprint09 for the pull request!

- 2016-11-15 16:57:16

This release targets Swift 3.0 / Xcode 8.0.

Added

  • Trim whitespace from each field (#8). Thanks florianheller for the proposal!

- 2016-09-24 16:37:16

This release targets Swift 3.0 / Xcode 8.0.

Added

  • Swift 3.0 support (#3, #6)

- 2016-08-21 03:50:26

This release targets Swift 2.2 / Xcode 7.3 & Swift 2.3 / Xcode 8.0.

Added

  • Swift 2.3 support (#5)

- 2016-08-21 03:23:36

This release targets Swift 2.2 / Xcode 7.3.

Breaking

  • Modified to use NSInputStream If you want to read the file. Please see the README.md for more details.

Improved

  • Change the algorithm to read the csv string.