CSVDecoder

public struct CSVDecoder

Simple in-memory CSV data representation decoder.

Compared to other formats, CSV representation is very limited. It doesn’t support decoding of nested values or direct decoding of primitive values. Unless the type to be decoded has a dedicated init(from: Decoder) method, it is only possible to decode an array of the type.

Here’s an example that decodes an array of simple structures:

struct Person: Decodable {
  var id: Int
  var name: String
}

let csv = """
id,name
1,"Thomas"
"2",Gina
""".data(encoding: .utf8)

let decoder = CSVDecoder()
let people = try? decoder.decode([Person].self, from: csv, encoding: .utf8)

Bug

  • Only the comma , separator character is supported.
  • First line is always assumed to be the header consisting of column names.
  • Initializes the decoder.

    Declaration

    Swift

    public init()
  • Decodes a top-level value of the given type from the provided CSV representation.

    CSV format doesn’t support decoding of nested values or direct decoding of primitive values. Using the compiler synthesized conformance to Decodable protocol, it is only possible to decode an array of this type from the CSV data.

    Throws

    A member of the CSVDecodingError if values requested from the payload are corrupted, or if the given data is not valid CSV.

    Declaration

    Swift

    public func decode<T>(_ type: T.Type, from data: Foundation.Data, encoding: String.Encoding)
    throws -> T where T : Decodable

    Parameters

    type

    Type of the value to decode.

    data

    CSV data to decode from.

    encoding

    Encoding used to convert raw CSV data to strings.

    Return Value

    A value of the requested type.