我有这种快速的美丽:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch {
print("shit happens")
}
当然我收到错误消息,因为出现错误。如何找出错误是什么? (是的,文件存在)
由于
答案 0 :(得分:2)
让catch
创建一个"错误"常量,与NSError兼容:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch let error as NSError {
print(error.localizedDescription)
}
您也可以使用catch
自动创建"错误"常数:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch {
print(error)
}