read a csv file in swift

To read a csv file in Swift, you can use the String(contentsOf:URL) method to read the contents of the file as a string. Then, you can split the string into an array of lines using the components(separatedBy:) method. Finally, you can split each line into an array of fields using the components(separatedBy:) method again.

Here's an example code snippet:

main.swift
if let url = Bundle.main.url(forResource: "filename", withExtension: "csv") {
    do {
        let contents = try String(contentsOf: url)
        let lines = contents.components(separatedBy: .newlines)
        
        for line in lines {
            let fields = line.components(separatedBy: ",")
            print(fields)
        }
    } catch {
        print("Unable to read file contents")
    }
}
402 chars
14 lines

In this example, replace "filename" with the name of your csv file (without the file extension). The for loop iterates over each line in the csv file, splitting it into an array of fields using the comma as the separator. The resulting array is then printed to the console.

Note that this example code assumes that the csv file is located in the main bundle of your app. If the file is located elsewhere, you'll need to modify the url variable accordingly.

gistlibby LogSnag