Swift错误处理:“无效模式”

时间:2016-07-17 09:13:54

标签: swift error-handling try-catch

我在CGPoint上有一个抛静态方法:

extension CGPoint {
  static func cornerPointsForRegularPolygon(withSideCount sideCount: Int, center: CGPoint, cornerDistance distance: CGFloat) throws -> [CGPoint] {
    guard sideCount > 2 else {
      throw PolygonConstructionError.invalidSideCount(sideCount)
    }
    guard distance > 0 else {
      throw PolygonConstructionError.invalidCenterToCornerDistance(distance)
    }

    //...
  }
}

cornerPointsForRegularPolygon引发的错误类型是:

extension CGPoint {
  enum PolygonConstructionError : ErrorProtocol {
    case invalidSideCount(Int)
    case invalidCenterToCornerDistance(CGFloat)
  }
}

我为cornerPointsForRegularPolygon编写了一个包含try-catch模式的测试:

func testCornerPointsForRegularPolygon() {
  do {
    let _ = try CGPoint.cornerPointsForRegularPolygon(withSideCount: 0, center: CGPoint.zero, cornerDistance: 10)
  } catch CGPoint.PolygonConstructionError.invalidSideCount(let count) {
    XCTAssertEqual(count, 0)
  } catch {
    XCTFail("Should have thrown error `PolygonConstructionError.invalidSideCount`")
  }
}

之前我曾多次使用过这种模式,但这次我收到错误 - Invalid pattern - catch CGPoint.PolygonConstructionError.invalidSideCount(let count)

这是什么意思,我该如何解决呢? 谢谢:))

更新

当我使用cornerPointsForRegularPolygon中的错误时,我得到以下内容: Errors

此外,我注意到在现有类型(例如CGPointUIBezierPath)的扩展中定义和抛出的错误类型会产生错误,而我自己类型中定义的错误类型则不会。

0 个答案:

没有答案