【发布时间】:2016-04-13 03:27:25
【问题描述】:
在下面的代码中,我试图访问位于我的主目录中的文件0.txt。主目录的路径保存在一个字符串中,并在调用时附加名称 0.txt(0 是一个引用计数器,它将在程序运行时更改值。为了这个问题,我会将其称为0)。
func loadfile(counter: Int) -> String { // counter here is assumed to be "0"
var contents = String()
var defaultpath = ("~/" as NSString).stringByExpandingTildeInPath as String
do {
contents = try String(contentsOfFile: defaultpath.stringByAppendingString(String("\(counter).txt")))
return contents
} catch {
print("For some reason, the file couldn't be accessed.")
return "failed"
}
}
但是,每次运行此代码块时,返回值都是failed 并打印For some reason, the file couldn't be accessed 行,即使~/0.txt 存在。有谁知道为什么会发生这种异常行为,如果是,我应该如何解决这个问题??
附带问题:有没有办法将 try-catch 块产生的错误打印到标准输出?
【问题讨论】: