Is it possible to make early exit in do-try-catch block? (Like `guard`)


(Vladimir Kelin) #1

It would be convenient to have do-try-catch block in "early-exit style". Like:

do-guard let encrypted = try cypher.encrypt(bytes) catch let e {
    print("Encryption error:", e)
    return // Thank Adrian for reminding

// Massive code

I may be wrong, but it's not implemented yet.

(Adrian Zubarev) #2

If I understand you correctly you want to sugar over this:

let value: Value
do {
  value = try getValue()
} catch {
  return // in your case this would be required

// use value here

Is that correct?

I pitched something like this myself before and IIRC this is also known by the community as guard catch.

(Vladimir Kelin) #3

Yes, thats exactly the sweetness that I want to achieve.

(Xiaodi Wu) #4
let result = Result { try getValue() }

guard case let .success(value) = result else {

(Adrian Zubarev) #5

Small note, this isn‘t officially availble for us to use as Swift 5 is not yet released, but one can create an own Result type meanwhile.

(Teva Merlin) #6

There is also:

guard let value = try? getValue() else {

// use value here

(Adrian Zubarev) #7

I personally came to the conclusion that guard catch would be confusing with guard else. What we should do instead is just allow a guard like syntax instead of the do body with 1-n comma separated list of throwing expressions.

  let value1 = try getValue(),
  let value2 = try getValue(),
  try throwingVoidFunction()
catch {

(Vladimir Kelin) #8

You can't see the error here.

(Teva Merlin) #9

I actually wrote it as a reply to the pieces of code posted by @xwu and @DevAndArtist, where the content of the error was also ignored (the difference being of course that in their code, the content of the error could be accessed if needed).

I should have written: “If it’s ok to ignore what the error is, there is also this approach.”
I love the fact that we have try? for some of those cases where you only care about whether there was an error and not about what the error was.