[swift-evolution] [Pitch] Guarding on enum values

Step C schristopher at bignerdranch.com
Wed Dec 23 17:31:08 CST 2015



> On Dec 22, 2015, at 11:58 PM, Andrew Duncan via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Motivation
> 
> The guard statement rescues us from the pyramid of doom, and lets our code hug the left margin more... if the failure case is false or nil. I'd like to guard against specific values in an enum, and get the same flattening of code flow. This generalizes Swift’s convenient handling of Optionals. (I have a hazy perception that this was mooted for 1.x, but can’t remember where I read it.)
> 
> The goal is to make error-handling by result-returning smoother. (I need say no more about side-effect NSError** parameters.) Consider everyone’s favorite enum example: 
> 
>    enum Result { 
>    case .Fail(String)      // Error message
>    case .Succeed(MyType)   // Something we use.
>    }
> 
> The Pitch (to avoid TL;DR)
> 
> I'd like to use something like this:
> 
>    guard case let .Succeed(m) = returnsResult() else {
>         return it
>    }
>    // Can safely use m, otherwise Result is passed back the call stack.

What about an enumeration with three cases? 

For example:

enum Result {
case Success
case Failure
case Cancelled
}




More information about the swift-evolution mailing list