Read a text file line by line in Swift?

前端 未结 6 732
广开言路
广开言路 2020-12-05 04:14

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 ca

6条回答
  •  青春惊慌失措
    2020-12-05 04:46

    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

提交回复
热议问题