A CSV parser written in Swift. Takes a String which contains CSV values and converts it into a 2D array of values. Algorithm's complexity: O(2n), where n is the number of characters in the given string.
let sampleText = """
john,UK,2000
jack,UK,2005
"""
let values = parse(string: sampleText)
print(values)
// prints: [["john", "UK", "2000"], ["jack", "UK", "2005"]]
It accepts a String
so if you have a CSV file in the resources, then you can get the text like this:
let file = "grades"
guard let url = Bundle.main.url(forResource: file, withExtension: "csv"),
let text = try? String(contentsOf: url, encoding: .utf8) else {
return
}
// Pass the text
let csvValues = parse(string: text)
print("CSV values: \(csvValues)")
- Handle the field(coloumn) names