[swift-evolution] [pitch] Make exceptions visible in guard's else block

Nick Keets nick.keets at gmail.com
Wed Nov 16 05:06:40 CST 2016

Hello all, I'm interested in a pattern to return failure, together with an
to explain why. I think that the "guard let x = x" discussion touched on
the issue,
but didn't really go in that direction.

Right now, optional and boolean results work nicely with guards, but you
only get
sucess/failure back. For example:

func foo() -> Int?
func bar() -> Bool
func baz(Int) -> Int?

let a = foo(),
let b = baz(a)
else {
// No information about what failed here
print("Something failed")

I see a lot of enum Result solutions being proposed, but they have the
problem of not having access to the error inside guards. For example:

enum Result<T> { case sucess(T), error(String) }

func foo() -> Result<Int>

guard case let .success(value) = foo() else {
    // Result is .error but we have no access to the error message here

I think a solution to this problem could be to allow "guard let try"
that make the error available inside the else statement. So you could write:

func foo() throws -> Int
func bar() -> Bool
func baz(Int) throws -> Int

let a = try foo(),
let b = try baz(a)
else {
// `error` is available here like in a catch block
print("Error: \(error.localizedDescription)")

A potential weirdness of this solution is that it appears indistinguishable
"guard let try?" (already available) if you are not interested in the error.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161116/937c2b55/attachment.html>

More information about the swift-evolution mailing list