Search code examples
iosarraysswifttextnsstring

Read a text file line by line in Swift?


I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?

TextFile.txt contains the following:

1. Banana 
2. Apple
3. pear
4. strawberry
5. blueberry
6. blackcurrant

The following is what currently have..

  if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
        var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
            if let content = (data){
                TextView.text = content
    }

If there is another way of doing this please let me know. It would be much appreciated.


Solution

  • Swift 3.0

    if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {
        do {
            let data = try String(contentsOfFile: path, encoding: .utf8)
            let myStrings = data.components(separatedBy: .newlines)
            TextView.text = myStrings.joined(separator: ", ")
        } catch {
            print(error)
        }
    }
    

    The variable myStrings should be each line of the data.

    The code used is from: Reading file line by line in iOS SDK written in Obj-C and using NSString

    Check edit history for previous versions of Swift.