【发布时间】: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