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

Swift - reading a file into a string array

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

我做错了什么吗?

谢谢,

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

let path = String(readLine()!)!

因此您尝试强制解包一个可选值,该值目前为 nil。您还应该使用另一种方法将数组转换为字符串。

我不知道你为什么需要从控制台读取。这个项目是命令行项目吗?不管怎样,用这个来调查这个问题:

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