Why does Regex.firstMatch et al. possibly throw?

The documentation doesn't say anything about that. In fact, shouldn't documentation for a function always explicitly say why it might throw?

1 Like

Looks like it mostly comes from: Throwing customization hooks by milseman · Pull Request #261 · apple/swift-experimental-string-processing · GitHub

One of the tests seems to imply that if you're adding some custom regex processing you might find throwing to be a useful failure signal of some sort.

Setting aside whether it should, it looks like the throws part was added as a consequence of a fairly low-level operation down in an internal type's method, Executor._match(_:from:using:). Sometimes it takes a while for that sort of change to bubble up to the documentation of the API, especially if the failure reason is easier to state for the underlying implementation reason rather than the reason at the call site.

This from @Michael_Ilseman is relevant: Inconsistance throwing behavior on String and Regex's xxMatch - #2 by Michael_Ilseman

The core regex operations can throw, because things like custom regex consumers can throw their own custom errors. Regex's hosted API will faithfully surface these failure reasons rather than squash them all into a single notion of failure via nil. This is useful for libraries and more advanced use cases.

The common case is to not care about how something failed to match. The API on string are collection algorithms that will coalesce all failure reasons into nil, meaning it failed. This is more convenient as the caller of these higher level operations care about match-or-not. If these threw, then all the call sites would be annotated with extra try? ceremony for little benefit.

5 Likes

Thanks for clearing it up :). I had actually neglected to look at the String functions and only considered the ones on Regex.