Read a text file line by line in Swift?

2019-01-13 20:12发布

问题:

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. blackcurrent

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
    }

also if there is another way, of doing this please let me know. Much appreciated

回答1:

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.



回答2:

Update for Swift 2.0 / Xcode 7.2

    do {
        if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
            let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)

            let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
            print(myStrings)
        }
    } catch let err as NSError {
        //do sth with Error
        print(err)
    }

Also worth to mention is that this code reads a file which is in the project folder (since pathForResource is used), and not in e.g. the documents folder of the device



回答3:

You probably do want to read the entire file in at once. I bet it's very small.

But then you want to split the resulting string into an array, and then distribute the array's contents among various UI elements, such as table cells.

A simple example:

    var x: String = "abc\ndef"
    var y = x.componentsSeparatedByString("\n")
    // y is now a [String]: ["abc", "def"]