我正在使用 NSFileManager
删除临时文件,如下所示:
let fm = NSFileManager()
fm.removeItemAtURL(fileURL)
// error: "Call can throw but it is not marked with 'try'"
我真的不在乎调用时文件是否存在以及它是否已被删除,随它去吧。
在不使用 do/catch
的情况下,告诉 Swift 忽略任何抛出的错误的优雅方式是什么?
最佳答案
如果你不关心成功与否,那么你可以调用
let fm = NSFileManager.defaultManager()
_ = try? fm.removeItemAtURL(fileURL)
来自 "Error Handling"在 Swift 文档中:
You use
try?
to handle an error by converting it to an optional value. If an error is thrown while evaluating thetry?
expression, the value of the expression isnil
.
removeItemAtURL()
返回“无”(又名 Void
),因此 try?
的返回值表达式是 Optional<Void>
.
将此返回值分配给 _
避免 “‘尝试?’的结果”未使用” 警告。
如果你只对通话的结果感兴趣而不是
抛出的特定错误然后你可以测试
try?
的返回值反对nil
:
if (try? fm.removeItemAtURL(fileURL)) == nil {
print("failed")
}
更新:从Swift 3 (Xcode 8)开始,您不需要虚拟分配,至少在这种特殊情况下不需要:
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)
编译时没有警告。
关于ios - 一种忽略方法抛出的任何错误的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32788155/