Xcode 7.1 beta: Content Of File Error

2020-05-04 11:26发布

问题:

I had just finished the final touches to my swift app. But after upgrading to Beta 7 its giving me errors for the 'ContentOfFile' String. can anyone help me understand how I can go about fixing this please?

here's what i've got ATM.

//Reads the Text File
    if var path = NSBundle.mainBundle().pathForResource("Chapters", ofType: "txt"){

        //Reads the Text File into one Huge String
        var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)

            //sets String content of the Text File as an Array. With each string start at \n (new line)
            if var content = (data){

                //from the mass string of data from the text file, Each chapter content is seperated by #
                var Chapters: [String] = content.componentsSeparatedByString("@")

                //without removing index in the beginning there will be an extra element printed in the array.
                Chapters.removeAtIndex(0)

Error Message: Cannot invoke initializer for type 'String' with an argument list of type '(contentsOfFile: String, encoding: UInt, error: NilLiteralConvertible)'

回答1:

You need to implement do try catch error handling. Try like this:

edit/update:

Swift 3 or later

if let fileURL = Bundle.main.url(forResource: "Chapters", withExtension: "txt") {
    do {
        let string = try String(contentsOf: fileURL, encoding: .utf8)
        var chapters = string.components(separatedBy: "@")
        chapters.removeFirst()
    } catch {
        print(error)
    }
}