https://github.com/zackify/swift-csv
A CSV Generator for Swift
https://github.com/zackify/swift-csv
Last synced: 9 months ago
JSON representation
A CSV Generator for Swift
- Host: GitHub
- URL: https://github.com/zackify/swift-csv
- Owner: zackify
- Created: 2020-03-09T23:02:48.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2024-03-14T19:07:17.000Z (almost 2 years ago)
- Last Synced: 2025-04-08T07:43:04.316Z (11 months ago)
- Language: Swift
- Size: 15.6 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# swift-csv
## Install
Add to your Package.swift dependencies:
```
.package(url: "https://github.com/zackify/swift-csv.git", from: "0.2.0")
```
## Example
Generate CSVs with dynamic column headings and row data.
If you have a data structure with unknown amount of values, it can be frustrating to make that fit into a CSV. For example, imagine a CSV with people, and an unknown number of addresses. With this library, you can return an array, and column headings will be calculated for you:
```swift
import SwiftCSV
let csv = SwiftCSV.generate(testRows) {
[
$0.text(name: "Name", value: $0.row.name),
$0.array(name: "Address", value: $0.row.addresses) { $0.street },
$0.text(name: "Phone number", value: $0.row.phoneNumber)
]
}
```
Here's the output:
```
"Name","Address","Address #2","Address #3","Phone number"
"Test","New York","California","","5493939393"
"Bob","Montana","California","Texas","483884828"
```
By naming the field `Address` the headings and rows fill in with empty data where needed.
In the example, testRows looks like this:
```swift
struct Address {
var street: String
}
struct Person {
var id: String
var name: String
var phoneNumber: String
var addresses: [Address]
}
let testRows = [
Person(
id: "1",
name: "Test",
phoneNumber: "5493939393",
addresses: [
Address(street: "New York"),
Address(street: "California"),
]
),
Person(
id: "1",
name: "Bob",
phoneNumber: "483884828",
addresses: [
Address(street: "Montana"),
Address(street: "California"),
Address(street: "Texas"),
]
)
]
```