Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Created March 9, 2020 15:22
Show Gist options
  • Save heestand-xyz/ca4fbd2a81461226a6c16ea3c45dfbd3 to your computer and use it in GitHub Desktop.
Save heestand-xyz/ca4fbd2a81461226a6c16ea3c45dfbd3 to your computer and use it in GitHub Desktop.
CSV
func csv(named name: String) -> [[String]]? {
guard let url: URL = Bundle.main.url(forResource: name, withExtension: "csv") else { return nil }
return csv(url: url)
}
func csv(url: URL) -> [[String]]? {
guard let text: String = try? String(contentsOf: url) else { return nil }
return csv(text: text)
}
func csv(text: String) -> [[String]] {
let trimmed: String = text.trimmingCharacters(in: .whitespacesAndNewlines)
let rows: [String] = trimmed.split(whereSeparator: { $0.isNewline }).map({ "\($0)" })
let table: [[String]] = rows.map({ $0.split(omittingEmptySubsequences: false, whereSeparator: { [",", ";"].contains($0) }).map({ "\($0)" }) })
return table
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment