Swift中非抛出函数的错误处理

时间:2017-12-10 12:38:36

标签: swift error-handling

我在处理非抛出函数(如重写方法,委托方法或dataSource方法)中的错误时遇到问题。我只想出记录错误,因为你知道这不是一个好的错误处理策略。有没有其他方法,方法等?谢谢。

编辑:

enum SomethingError : Error{
    case somethingFailed
}

var anObject : AnObject?

........
........


public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            throw SomethingError.somethingFailed
            //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
        }

      .....
      .....

      return cell
}

你不能这样做,因为:collectionView:cellForItemAt:indexPath不是一个抛出函数,它必须返回一个单元格。我怎么能在这里发现错误?这是个问题。只能通过记录?

编辑:我知道我可以使用if let但是我想要抓住/抛出;处理错误。

1 个答案:

答案 0 :(得分:2)

您无法在未明确要求的协议的实现中传播错误。

您可以在同一个实现中throw/catch或只是调用一个方法来处理错误。在您的示例中,您可以使用throw/catch,如下所示:

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      do {

          guard let anObject = anObject else {
              throw SomethingError.somethingFailed
              //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
      } catch SomethingError.somethingFailed {
          // handle the error here
      }

      .....
      .....

      return cell
}

只有一个功能,它将是这样的:

func handleError() {
    // handle error
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            handleError()
            return
        }

      .....
      .....

      return cell
}

有关swift中错误处理的更多信息,请参阅:The Swift Programming Language: Error Handling