[swift-evolution] Idea: Extend "guard" to try-statements, with a catch block

Chris Lattner clattner at apple.com
Tue Mar 1 00:34:40 CST 2016


On Feb 29, 2016, at 12:09 PM, Jacob Bandes-Storch via swift-evolution <swift-evolution at swift.org> wrote:
> I propose extending guard-statements to handle errors without using the optional "try?" and without a do-block, by allowing the expression to throw, and offering "catch" instead of "else":
> 
>     // func foo() throws -> T ...
>     guard let x = try foo catch {
>         print("the error was: \(error)")  // the "error" parameter is available here
>         // the compiler does not allow control flow to escape this block
>     }
>     // control flow cannot reach here if foo() threw an error

I don’t think that this syntax makes sense, because you’re changing "guard let x = ” to not test an optional.  The syntax you’re searching for seems more consistent as a modifier on var/let itself:

// func foo() throws -> T ...
let x = try foo() catch {
        print("the error was: \(error)")  // the "error" parameter is available here
        // the compiler does not allow control flow to escape this block
}

The guard form of this would still make sense, but the existing “guard let” and “guard case” matching should work as it does.  For example, something like this should be allowed:

// func bar() throws -> T?
guard let x = try bar() else {
        // this runs if ‘bar’ returns nil.
        // the compiler does not allow control flow to escape this block
} catch {
        print("the error was: \(error)")  // the "error" parameter is available here
        // the compiler does not allow control flow to escape this block
}

More generally, the “guard” form would be workable on anything that takes a stmt-condition.  This brings “if" and “while” into the mix.

-Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160229/ef1b407f/attachment.html>


More information about the swift-evolution mailing list