Skip to content

Commit 8542d5d

Browse files
authored
Update README with CaseIterable tip
1 parent 7223016 commit 8542d5d

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,7 @@ struct Student: Codable {
574574
var age: Int
575575
var hasPet: Bool
576576
577-
private CodingKeys: Int, CodingKey {
577+
private enum CodingKeys: Int, CodingKey {
578578
case name = 0
579579
case age = 1
580580
case hasPet = 2
@@ -584,6 +584,31 @@ struct Student: Codable {
584584
585585
> Using integer coding keys has the added benefit of better encoder/decoder performance. By explicitly indicating the field index, you let the decoder skip the functionality of matching coding keys string values to headers.
586586
587+
To generate type-safe name header rows you can use an enum with `String` rawValues.
588+
589+
```swift
590+
struct Student: Codable {
591+
var name: String
592+
var age: Int
593+
var hasPet: Bool
594+
595+
private enum CodingKeys: String, CodingKey, CaseIterable {
596+
case name = "name"
597+
case age = "age"
598+
case hasPet = "hasPet"
599+
}
600+
}
601+
```
602+
603+
Then configure your encoder with explicit headers.
604+
605+
```swift
606+
let encoder = CSVEncoder {
607+
$0.headers = Student.CodingKeys.allCases.map({ $0.rawValue })
608+
}
609+
```
610+
611+
587612
</p></details>
588613
<details><summary>A CSV is a long list of rows/records.</summary><p>
589614

0 commit comments

Comments
 (0)