CSVDecoder
public final class CSVDecoder
Decodes CSV document data to Swift types.
This example shows how a simple Person
type will be decoded from a CSV document.
Personconforms to
Codable, so it is compatible with both the
CSVEndocderand
CSVDecoder`.
struct Person: Codable {
let firstName: String,
let lastName: String,
let age: Int
}
let csv = """
"firstName","lastName","age"
"Grace","Hopper","113"
"Linus","Torvold","50"
"""
let data = Data(csv.utf8)
let people = try CSVDecoder.sync.decode(Person.self, from: data)
print(people.map { $0.firstName }) // Prints: `["Grace","Linus"]`
-
The decoding options to use when decoding data to an object.
This is currently used to specify how
nil
andBool
values should be handled.Declaration
Swift
public var decodingOptions: CSVCodingOptions
-
Creates a new
CSVDecoder
instance.Declaration
Swift
public init(decodingOptions: CSVCodingOptions = .default)
Parameters
decodingOptions
The decoding options to use when decoding data to an object.
-
Creates a
CSVSyncDecoder
with the registered encoding options.This decoder is for if you have whole CSV document you want to decode at once.
Declaration
Swift
public var sync: CSVSyncDecoder
-
Creates a
CSVAsyncDecoder
instance with the registered encoding options.This decoder is for if you have separate chunks of the same CSV document that you will be decoding at different times.
Declaration
Swift
public func async<D>(for type: D.Type = D.self, length: Int, _ onInstance: @escaping (D) -> ()) -> CSVAsyncDecoder where D: Decodable
Parameters
type
The
Decodable
type that the rows of the CSV document will be decoded to.length
The content length of the whole CSV document.
onInstance
The closure that is called when an instance of
D
is decoded from the data passed in.Return Value
A
CSVAsyncDecoder
instance with the current encoder’s encoding options and the.onInstance
closure as its callback.