Why doesn't the String conform to the Error protocol?

Why doesn't the String conform to the Error protocol?

Because strings are not, in general, errors.

6 Likes

Why do you think it should?

As someone who has written this conformance myself a few times: probably because it's only valuable in small programs. It's great for a CLI, where the errors are typically unrecoverable and presented to the user immediately. It's inappropriate in virtually any other context:

  • if the error is recoverable, you probably want an enum that lets the caller of the function easily find out what happened (with a switch statement, vs. string parsing) so they can respond appropriately
  • in a production iOS app that makes extensive use of throws you probably want to report the errors, and you'll probably want to include extra context like #filepath, #function, and #line of the original error, as opposed to the reporter of the error

With all that said, ABI stability rules mean that it is probably not possible to add this conformance (backporting might change this, I'm not familiar enough with how this works to know for sure).

1 Like

It's not wise to add conformances to the protocol you don't own to the types you don't own. (I'm also guilty of that.)

This is true in the general case, and yeah I probably should have mentioned in my original comment.

But I am adding the conformance in small CLI programs. They have no dependencies, so no one else is going to add the conformance. ABI stability probably means the stdlib can't add it. I'm not aware of any other way this can go wrong. Even if it somehow was added, it would be trivial to clean up my own conformance.

3 Likes

Just to be clear, the stdlib is free to add conformances to types whenever it wants because adding a conformance is not an ABI breaking change within the stdlib. In practice however, we probably won't add conformances to existing types due to frameworks or apps who assumed that the stdlib would never add said conformance and then we'd be breaking those above us who made such assumptions. The stdlib wants to add a bunch of missing conformances to some of our types, but due to fear of breaking others we're very hesitant to do so. In general, just make a wrapper over the type you don't own if you want to add a retroactive conformance.

6 Likes

Thanks for the correction. I think I conflated some documentation about source compatibility with ABI stability, or maybe I'm just totally misremembering.

Eh I think you were basically right. We are "allowed" to add it but in practice we probably can't.

1 Like