[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
error
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?

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

I see a lot of enum Result solutions being proposed, but they have the
fundamental
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
    return
}

I think a solution to this problem could be to allow "guard let try"
statements
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

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

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

Thoughts?
-------------- 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