CSVEncoder

public final class CSVEncoder

Encodes Swift types to CSV data.

This exampls shows how multiple instances of a Person type will be encoded to CSV data. Person conforms to Codable, so it is compatible with both the CSVEndocder and CSVDecoder.

struct Person: Codable {
   let firstName: String,
   let lastName: String,
   let age: Int
}

let people = [
    Person(firstName: "Grace", lastName: "Hopper", age: 113),
    Person(firstName: "Linus", lastName: "Torvold", age: 50)
]

let data = try CSVEncoder().sync.encode(people)
print(String(decoding: data, as: UTF8.self))

/* Prints:
 "firstName","lastName","age"
 "Grace","Hopper","113"
 "Linus","Torvold","50"
*/
  • The encoding options the use when encoding an object.

    Currently, this decideds how nil and bool values should be handled.

    Declaration

    Swift

    public var encodingOptions: CSVCodingOptions
  • Creates a new CSVEncoder instance.

    Declaration

    Swift

    public init(encodingOptions: CSVCodingOptions = .default)

    Parameters

    encodingOptions

    The encoding options the use when encoding an object.

  • Creates a CSVSyncEncoder using the registered encoding options.

    This encoder is for if you have several objects that you want to encode at a single time into a single document.

    Declaration

    Swift

    public var sync: CSVSyncEncoder
  • Creates a new CSVAsyncEncoder using the registered encoding options.

    This encoder is for if you have multiple objects that will be encoded separately, but into a single document.

    Declaration

    Swift

    public func async(_ onRow: @escaping ([UInt8]) -> ()) -> CSVAsyncEncoder

    Parameters

    onRow

    The closure that will be called when each object passed into the encoder is encoded to a row.

    Return Value

    A CSVAsyncEncoder instance with the current encoder’s encoding options and the onRow closure as its callback.