ios - 一种忽略方法抛出的任何错误的优雅方法

标签 ios swift exception exception-handling

我正在使用 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 the try? expression, the value of the expression is nil.

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/

相关文章:

ios - NSNumberFormatter 0.1 问题

ios - 添加全屏 View 作为 View Controller 的 subview

ios - Core Data Stack 应该从 NSObject 继承吗?为什么?

javafx 时间线中的 java.util.ConcurrentModificationException

ios - 显示来自 Core Data 的 NSSet 数据

ios - 在 iPhone 应用程序中单击按钮时显示拨号屏幕

ios - 调整图像选定区域的大小

c# - 仅在一台电脑上出现异常,在其他电脑上工作正常

c# - 不要在堆栈跟踪中显示构建机器的文件路径

ios - 使用swift动态设置TableViewCell的大小