Xcode 7.1 beta: Content Of File Error

倖福魔咒の 提交于 2019-12-02 18:33:01

问题


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)
    }
}


来源:https://stackoverflow.com/questions/32598208/xcode-7-1-beta-content-of-file-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!