简体   繁体   中英

Import and read text file in Swift

I tried all the different approaches posted here, and got various errors on each: https://codereview.stackexchange.com/questions/100773/load-text-file-into-an-array-in-swift (Are these up-to-date?)

Most recently, I tried:

    func linesFromResourceForced(fileName: String) -> [String] {

    let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)!
    let content = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
    return content.componentsSeparatedByString("\n")
}

let lines = linesFromResourceForced("file.txt")
print (lines)

And got these errors: "let lines = " --> Cannot convert value of type 'String' to expected argument type 'ViewController' print(lines) --> Expected declaration

What am I doing wrong? I would also appreciate any other recommendations for the simplest way to import and read text. Thanks!

Let's say you want to load the lines from the text file in an iOS app.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let lines = linesFromResourceForced("file.txt")
        print (lines)
    }

    func linesFromResourceForced(fileName: String) -> [String] {

        let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)!
        let content = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        return content.componentsSeparatedByString("\n")
    }
}

You need to declare the function in your class, and call it in the context of another function. So when your view controller loads, viewDidLoad , it will call linesFromResourceForced to load up your array of lines and print them in that context.

Updated for Swift 4+

            let path = Bundle.main.path(forResource: "myfile.txt", ofType: nil)!
            let myStringText = try String(contentsOfFile: path, encoding: String.Encoding.utf8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM