ios - Swift 中的 func 会抛出什么类型的错误?

标签 ios swift error-handling throws

我在 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/

相关文章:

error-handling - 参数在序言中没有充分实例化

php - 使用jQuery发布时从函数获取数据

ios - 使用 CIAdditionCompositing 添加纯黑色时的预期行为?

ios - 不支持的 URL 错误代码 -1002

javascript - Keydown 允许数字但不能在 iPhone 上换档符号

ios - 如何滚动到 UITableView 的确切末尾?

ios - GeoCoder 使用地址获取经度和纬度

python - Facebook Selenium如何获得喜欢的人数

ios - 有没有办法在不启动应用程序的情况下从 Siri 启动应用程序内购买,而是在 Intents Extension 中运行代码?

swift - @在swift中是什么意思?