【问题标题】:What kinds of errors does a func throw out in Swift?函数在 Swift 中抛出了哪些类型的错误?
【发布时间】:2017-09-02 08:59:24
【问题描述】:

我在 Apple 的文档中看到一些方法会抛出错误。但我找不到任何关于它抛出什么的信息。

喜欢下面的这种方法。它在 FileManager 类中。

func moveItem(at srcURL: URL, to dstURL: URL) throws

我想知道它会抛出什么样的错误。我在哪里可以获得相关信息?

【问题讨论】:

  • 你不觉得这是google的问题吗?
  • 我试过了。但我没有得到答案。可能我还没搞清楚关键词。

标签: ios swift error-handling throws


【解决方案1】:

与 Java 不同,throws 声明需要一个类型,在 Swift 中你不会知道会抛出什么类型的 Error。你唯一知道的是对象符合Error-protocol。

如果您知道某个函数会抛出一个特定的 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
    }
}

【讨论】:

  • 是的,这些信息对我很有用。有没有办法知道它符合什么协议?我想知道失败时发生了什么。
  • 这是否意味着我应该从catch 块中获取信息,而不是在catch 块中某事?
  • 在您的catch-block 中,将有一个名为error 的局部变量。这符合协议Error。如果方法的文档表明某个对象(假设它被称为CustomError)被抛出,您必须使用as?error 强制转换为该对象和/或检查类型如果error 使用@ 987654336@
  • 我知道如何在我的代码中抛出CustomError。但我仍然对 Apple 的文档存有疑虑。 Apple 框架中的所有类都符合Error 协议吗?如果没有,你能告诉我一个而不是指示某个对象(如CustomError)吗?我还没有找到任何人。 :(
  • 在 Swift 中,函数抛出的任何错误都需要符合Error-protocol。 The Swift Programming Language - Representing and Throwing Errors 如果函数的文档表明某个对象(如CustomError(将符合Error)被抛出,您可以检查对象的类型,就像我添加到我的答案中的示例一样
猜你喜欢
  • 1970-01-01
  • 2019-03-08
  • 2018-03-11
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
相关资源
最近更新 更多