【问题标题】:Swift - reading a file into a string arraySwift - 将文件读入字符串数组
【发布时间】:2017-04-27 02:19:39
【问题描述】:

将项目文件夹中的文件读入String 数组时遇到问题。

这是我的代码:

 func readfile() -> [String] {
print("Please enter the name of your file")
let path = String(readLine()!)!
var array: [String]?

do {
    // Read an entire text file into an NSString.
    if let path = Bundle.main.path(forResource: path, ofType: "txt"){
        let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
        array = data.components(separatedBy: ",")
        print(array!)
    }
} catch let err as NSError {
    print("Unable to read the file at: \(path)")
    print(err)
}
return array! // I get a fatal error here, "fatal error: unexpectedly found nil while unwrapping an Optional value"

我做错了什么吗?

谢谢,

【问题讨论】:

  • 使用调试器并单步调试代码。
  • 因为数组不包含任何数据,您正在强制解开可选值。

标签: arrays swift file-handling


【解决方案1】:

你不能在函数返回值之前调用函数并使用它的值

let path = String(readLine()!)!

所以你尝试强制解开一个可选值,该值目前为 nil。此外,您应该使用另一种方式将数组转换为字符串。

【讨论】:

  • 仅供参考 - 错误不是来自您答案中的行。它来自答案代码的最后一行。
  • @rmaddy 抱歉打扰。实际上错误就在那条线上。我运行了他的代码,发现let path = String(readLine()!)! 产生了错误。
  • @nayem 我的评论基于问题中发布的代码。代码中有一条注释清楚地说明错误在最后一行。您是否在 macOS 命令行应用程序或 Linux 下尝试过代码?它的行为可能不同。
【解决方案2】:

我不知道你为什么需要从控制台读取。这个项目是命令行项目吗?无论如何,使用它来调查问题:

func readfile() -> [String] {
    print("Please enter the name of your file")

    let filename = String(readLine()!)!
    var array: [String]?

    if let path = Bundle.main.path(forResource: filename, ofType: "txt") {
        do {
            let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
            array = text.components(separatedBy: ",")
            // print(array)
            return array!
        } catch {
            print("Failed to read text from: \(filename)")
        }
    } else {
        print("Failed to load file from app bundle: \(filename)")
    }
    return [""]
}

【讨论】:

  • 我刚刚使用 macOS 命令行模板做了一个测试项目。只要您实际上向正在运行的应用程序提供了一些文本,此问题中发布的代码就会在最后一行 (return array!) 上失败。问题不在于对readLine() 的调用。
  • @rmaddy 好吧,现在我明白了。问题实际上是从Main Bundle 获取资源的完整路径名。它不执行 if let path = Bundle.main.path(forResource: path, ofType: "txt") ,所以 arraynil
  • 很明显,问题在于为捆绑包传递了正确的值。 OP 在发布前提供有用的详细信息或调试方面做得很差。
  • @rmaddy 是的。顺便说一句,命令行项目不是可以从Main Bundle读取吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
相关资源
最近更新 更多