Swift - 将文件读入字符串数组

时间:2017-04-27 02:19:40

标签: arrays swift file-handling

将项目文件夹中的文件读入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"

我做错了吗?

谢谢,

2 个答案:

答案 0 :(得分:0)

在函数返回值

之前,无法调用函数并使用其值
let path = String(readLine()!)!

所以你试着强行打开一个当前为零的可选值。您还应该使用另一种方法将数组转换为字符串。

答案 1 :(得分:0)

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

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 [""]
}