一种优雅的方式来忽略方法抛出的任何错误 [英] An elegant way to ignore any errors thrown by a method

查看:153
本文介绍了一种优雅的方式来忽略方法抛出的任何错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NSFileManager 删除一个临时文件:

I'm removing a temporary file with NSFileManager like this:

let fm = NSFileManager()
fm.removeItemAtURL(fileURL)
// error: "Call can throw but it is not marked with 'try'"

我不在乎文件是否在呼叫发生时,如果它已被删除,那么就这样。

I don't really care if the file is there when the call is made and if it's already removed, so be it.

如果没有使用 do / catch

推荐答案

如果您不关心成功,可以致电

If you don't care about success or not then you can call

let fm = NSFileManager.defaultManager()
_ = try? fm.removeItemAtURL(fileURL)

错误处理


您使用 try?通过将其转换为可选值来处理错误。
如果在评估 try?表达式时抛出错误,表达式的值
nil

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()返回nothing(aka Void ),因此 try?表达式的返回值为可选< Void>
将此返回值分配给 _ 避免try的结果未使用警告。

The removeItemAtURL() returns "nothing" (aka Void), therefore the return value of the try? expression is Optional<Void>. Assigning this return value to _ avoids a "result of 'try?' is unused" warning.

如果您只对调用结果感兴趣但不在
中抛出的特定错误,则可以测试
返回值尝试? nil

If you are only interested in the outcome of the call but not in the particular error which was thrown then you can test the return value of try? against nil:

if (try? fm.removeItemAtURL(fileURL)) == nil {
    print("failed")
}






更新:截至 Swift 3(Xcode 8),您不需要至少在这种特殊情况下,虚拟分配:


Update: As of Swift 3 (Xcode 8), you don't need the dummy assignment, at least not in this particular case:

let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)

编译没有警告。

这篇关于一种优雅的方式来忽略方法抛出的任何错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆