我在 Apple 文档中看到某些方法会抛出错误。但我找不到任何有关它抛出的信息。
就像下面这个方法。它在 FileManager 类中。
func moveItem(at srcURL: URL, to dstURL: URL) throws
我想知道它会抛出什么类型的错误。从哪里可以获得相关信息?
最佳答案
与 Java 中的 throws
声明需要类型不同,在 Swift 中,您不知道将抛出什么类型的 Error
。您唯一知道的是该对象符合 Error
协议(protocol)。
如果您知道函数会抛出特定的错误
(因为它有详细记录),您将需要正确地转换捕获的对象。
示例:
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
}
}
关于ios - Swift 中的 func 会抛出什么类型的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43270266/