Reading a file in Swift

A couple of month ago I found this algorithms course on Coursera. I remembered how much I liked algorithms and I thought it would be good to refresh my knowledge, so I signed up for it. Even though I don’t get to implement algorithms in my day to day job, I still think they are very useful and give you ideas about how to approach any problem. Each week there is a programming assignment and the best part about it is that you get to choose which language you want to use. So of course I decided to use Swift 3.

One of the first things I needed to solve my weekly assignments was a way to read input files. In particular, I had a file with lots and lots of numbers and I wanted to read it into an array of integers.

The following piece of code works with Swift 3 and iOS 10:

    func read(fileName: String) -> [Int] {
        guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else {
            return [Int]()
        do {
            let numbers = try String(contentsOfFile: path).components(separatedBy: "\n")
                .flatMap {Int($0)}
            return numbers
        } catch {
            return [Int]()

This will read a file that has been added to your Xcode project. It will assume that the numbers are all on different lines, but that can be easily changed.

The code is really simple. It uses the main bundle to get the path to the file. Then it reads all the content of the file in a String. Next, it splits the string into components. Notice how the separator used here is the new line character. If the numbers are separated by space or comma it’s easy to just change the separator and this will still give you all the string components.

Now we have an array of strings and we want to transform them into an array of Int. This sounds like a job for a map or a flatMap, because we want to apply the same transformation to each element of the array. I decided to use flatMap because I’m pretty sure that my file will only contain numbers and I don’t really want to deal with error handling right now.

And voila, there you have it: an array full of Ints. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *