Skip to content

Instantly share code, notes, and snippets.

@erica
Created June 27, 2017 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/e5c76423e260acfb2ae3827105084e5f to your computer and use it in GitHub Desktop.
Save erica/e5c76423e260acfb2ae3827105084e5f to your computer and use it in GitHub Desktop.

Introducing Guard-Catch

  • Proposal: SE-TBD
  • Author(s): Soroush Khanlou
  • Status: tbd
  • Review manager: tbd

Introduction

This proposal introduces a guard-catch statement to Swift, that is congruent to the existing guard-else statement with error catching support.

This proposal was first discussed on the Swift Evolution list in the TBD thread.

Motivation

There is no natural way to incorporate a throwing request into a guard without applying try? and discarding the error. Introducing guard-catch allows you to retrieve a successful value and handle a failure without losing error information.

In the current Swift language design, you can only achieve this approach by:

  • discarding the thrown error; or
  • embedding the guard statement into a do-catch scope.

Neither produces a satisfactory or elegant solution for using throwing calls within a guard statement.

Design

The statement derives from the guard-else grammar, substituting a catch clause for else, where the error is pre-defined and ready to use.

guard let value = try throwingFunction() 
    catch { 
        // handle error here, then leave scope
        print (error); return 
    }

As with guard-else, the catch clause must leave scope after handling the error.

Impact on Existing Code

This change is purely additive.

Alternatives and Future Directions

Not incorporating this statement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment