[swift-evolution] [Pitch] Use enums as enum underlying types

Félix Cloutier felixcca at yahoo.ca
Fri Dec 18 16:26:09 CST 2015


In the context of error handling, a "sub-enum" (a term I might use again to describe enum-backed enums) is an easy and scalable way to tailor the error reporting interface of a function. If David Owens II's annotated throws proposal <https://github.com/owensd/swift-evolution/blob/master/proposals/allow-type-annotations-on-throw.md> goes in, you can make an enum that has just the errors that your function can raise and you don't need to bother catching the rest.

Without it, taking your example, if I have a function that can throw NetworkException.NoInternetError, the annotation will still be NetworkException and you'll need a catch clause for SecurityError (or a catch-all) to be exhaustive. If you add a new NetworkException value, you need to update every call site to catch that value (or, again, use a catch-all). A sub-enum tailored to the function would increase resilience to changes in the underlying enum.

Maybe that tailored enum could even be synthesized by the compiler. That would be very cool for internal/private interfaces. (I'm not sure how the enum resilience thing Chris talks about will play out, so I wouldn't suggest that for public interfaces yet.)

Félix

> Le 18 déc. 2015 à 14:21:35, Sean Heber via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> This worked for me:
> 
> enum NetworkException: ErrorType {
>    case NoInternetError, SecurityError
> }
> 
> enum ParseException: ErrorType {
>    case FailedResponse(statusCode: Int)
>    case EmptyResponse
>    case MissingField(fieldName: String)
> }
> 
> enum ChangePictureError: ErrorType {
>    case Network(NetworkException)
>    case Parse(ParseException)
> }
> 
> func thing() throws {
>    throw ChangePictureError.Parse(.FailedResponse(statusCode: 401))
> }
> 
> func thing2() {
>    do {
>        try thing()
>    } catch ChangePictureError.Parse(.FailedResponse(statusCode: 401)) {
>        print("401")
>    } catch {
>        print("some other error")
>    }
> }
> 
> I must admit that I’ve generally avoided exceptions (aka using Java) throughout my entire programming career thus far and so don’t have extensive experience with this sort of situation. :)
> 
> l8r
> Sean

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/930ac239/attachment.html>


More information about the swift-evolution mailing list