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.swift402 chars14 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