[Pitch] Returning errors from #expect(throws:)

Swift Testing includes overloads of #expect() and #require() that can be used to assert that some code throws an error. They are useful when validating that your code's failure cases are correctly detected and handled. However, for more complex validation cases, they aren't particularly ergonomic. This proposal seeks to resolve that issue by having these overloads return thrown errors for further inspection.

Read the full pitch here.

6 Likes

Looking forward to this for the reasons outlined in the proposal. Being able to do this a little more ergonomically will be nice!

Out of curiosity, would it still be possible in the future to also add variants that use typed throws to deduce the error type or would that end up being ambiguous?

If you wanted to rely on type inference to avoid the throws: argument, you'd end up with something like:

#expect {
  try foo()
}

Which would be ambiguous to the reader even if the compiler understood. (And no, we don't want to rename it #expectThrows {} :grimacing:.)

Embedded Swift on the other hand will require overloads that use typed throws, but that's beyond the scope of this pitch as we don't support Embedded Swift yet.

The existing API (including the proposed changes) should be sufficient here, but if there's a use case you know of that would require typed throws, let me know!

Indeed, I was only wondering if inferring the type for typed throws cases would work or end up being confusing as you mention. So your explanation answered my question. :slight_smile: