一个func在Swift中抛出什么样的错误?
问题描述:
我看到一些方法抛出Apple的文档中的错误。但是我找不到任何关于它抛出的信息。一个func在Swift中抛出什么样的错误?
像下面这种方法。它在FileManager类中。
func moveItem(at srcURL: URL, to dstURL: URL) throws
我想知道它会抛出什么样的错误。我在哪里可以获得相关信息?
答
与Java不同,在throws
声明需要类型的情况下,在Swift中,您将不知道将会抛出什么类型的Error
。您唯一知道的是该对象符合Error
-协议。
如果你知道一个函数抛出一个证书Error
(因为它有很好的文档),你将需要正确地转换捕获的对象。
例子:
do {
try moveItem(from: someUrl, to: otherUrl)
} catch {
//there will automatically be a local variable called "error" in this block
// let's assume, the function throws a MoveItemError (such information should be in the documentation)
if error is MoveItemError {
let moveError = error as! MoveItemError //since you've already checked that error is an MoveItemError, you can force-cast
} else {
//some other error. Without casting it, you can only use the properties and functions declared in the "Error"-protocol
}
}
你不觉得这是谷歌的一个问题? –
我试过了。但我没有得到答案。也许我还没有弄清楚关键词。 – Matt