【问题标题】:Xcode 7.1 beta: Content Of File ErrorXcode 7.1 beta:文件内容错误
【发布时间】:2015-12-12 10:14:29
【问题描述】:

我刚刚完成了我的 swift 应用程序的最后润色。但是在升级到 Beta 7 之后,它给了我“ContentOfFile”字符串的错误。谁能帮助我了解如何解决这个问题?

这是我的 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)

错误消息:无法使用类型为“(contentsOfFile:String,编码:UInt,错误:NilLiteralConvertible)”的参数列表调用类型“String”的初始化程序

【问题讨论】:

  • Xcode 6 beta 7 你是认真的吗?
  • 哈哈哈我的错。那是一个错字
  • 你应该下载 Xcode 7 GM
  • 你需要实现 do try catch 并删除最后一个参数(错误)
  • 试过了。没用

标签: swift xcode6 text-files xcode7.1beta


【解决方案1】:

您需要实现 do try catch 错误处理。试试这样:

编辑/更新:

Swift 3 或更高版本

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

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多