Working with files in Swift


(Gábor Sebestyén) #1

This question might sound easy but I'm a bit uncertain on this.

I want to write simple command line Swift utilities / prototypes that work both on macOS and Linux but I don't have experiences in manipulating files directly like reading JSON / CSV content or processing a text line by line, etc.

What's the best way to do that? Does Foundation provide enough convenience or should I reach out to cool 3rd party libs? Which one would you recommend?
I appreciate your suggestions.

(Genaro Chris) #2

I think you should check out both FileHandle and FileManager classes from the standard library for your file operation and handling.


Try this one SwiftShell

(Quinn “The Eskimo!”) #4

That really depends on what specific facilities you need. Let’s look through the list you posted:

  • General file and directory manipulation — Foundation handles this well.

  • Processing a text file line by line — If the text file is small, it’s find to read in the whole thing, split it into lines, and then process it line by line. If the text file is too large for memory, things get more complex.

  • Reading JSON — Swift has this well covered.

  • Reading CSV — That depends on the specifics of your CSV (CSV isn’t really a file format, it’s a fleet of related file formats all sailing in roughly the same direction). If you have a simple CSV then reading the file line-by-line and then parsing each line is feasible. If you want to deal with arbitrary CSVs, it’s probably worth looking at a library.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

(Gábor Sebestyén) #5

I think I'd go for Foundation first and see how it fit my needs.
Thanks for the suggestions!